loading...

Train wagons πŸšƒ.πŸšƒ.πŸšƒ

codingunicorn profile image Coding Unicorn πŸ¦„ ・1 min read

Train wagons

Alt Text

Most developers know only one way of navigating a JSON object. This approach is called "train wagons". Some people call it "train wrecks":

promise
β €.then((response) => response.data.users[0].name) // πŸšƒ.πŸšƒ.πŸšƒ.πŸšƒ
β €.then(console.log);

This approach is works best when you want to return "intact" data, without transforming it. It's also the fastest solution.

But there is also another approach based on destructuring, where each "wagon" appears on its own line:

promise
β €.then(({ data }) => data)
β €.then(({ users }) => users)
β €.then(([ firstUser ]) => firstUser)
β €.then(({ name = 'πŸ¦„'}) => name)
β €.then(console.log);

This approach is slighly slower, but it has certain benefits:

  • you can give each wagon a name (user[0] becomes firstUser)
  • you can transform each wagon, before passing it down
  • you can provide a default value for each wagon (name = 'πŸ¦„')
  • it's elegant :-)

πŸ’‘ Both train wagons and destructuring have the right to exist. Each style has its own strengths and weaknesses. Choose the one that suits your situation best.

Posted on by:

codingunicorn profile

Coding Unicorn πŸ¦„

@codingunicorn

Hi!✌(β—•β€Ώ-)✌ My name is Julia (also known as coding_unicorn on Instagram). I'm a full-stack developer specializing in Java and JavaScript.

Discussion

markdown guide
 

You can also write the second approach without promises (because there is nothing async after the first element) and it's a bit faster :)

promise.then(({data})=>{
      const {users} = data
      const [firstUser] = users
      const {name="mike"} = firstUser
})

or if you just care about firstUser:

promise.then(({data: {users: [firstUser]}})=>{
     const {name} = firstUser
})