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

.then((response) =>[0].name) // 🚃.🚃.🚃.🚃
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:

.then(({ data }) => data)
.then(({ users }) => users)
.then(([ firstUser ]) => firstUser)
.then(({ name = '🦄'}) => name)
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.

Top comments (2)

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
Coding Unicorn 🦄

Love it!

Want to rep DEV and be comfy at the same time?

Check out our classic DEV shirt — available in multiple colors.