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

pic
Editor 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
})