DEV Community


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":

.then((response) =>[0].name) // 🚃.🚃.🚃.🚃

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:

.then(({ data }) => data)
.then(({ users }) => users)
.then(([ firstUser ]) => firstUser)
.then(({ name = '🦄'}) => name)

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)

Editor guide
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 :)

      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
codingunicorn profile image