DEV Community

Coding Unicorn 🦄
Coding Unicorn 🦄

Posted on

Train wagons 🚃.🚃.🚃

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (2)

Collapse
miketalbot profile image
Mike Talbot

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
})
Collapse
codingunicorn profile image
Coding Unicorn 🦄 Author

Love it!