DEV Community

Muhammad Awais
Muhammad Awais

Posted on

6 2

Converting Object to an Array

Problem

Sometimes what if you received an object of objects rather than array of objects from backend as a response, so how you will render that object of objects data using iterator of loop ?

Solution

Finally, with ES2017, it's official now! We have 3 variations to convert an Object to an Array 🎊

The array has an array of methods (sorry, bad pun 😝). So by converting the object into an array, you have access to all of that. Woohoo πŸ₯³

ES6 - Object.keys

const numbers = {
  one: 1,
  two: 2,
};

Object.keys(numbers);
// [ 'one', 'two' ]

Object.values(numbers);
// [ 1, 2 ]

Object.entries(numbers);
// [ ['one', 1], ['two', 2] ]
Enter fullscreen mode Exit fullscreen mode

Object.entries + Destructuring

const numbers = {
  one: 1,
};

const objectArray = Object.entries(numbers);

objectArray.forEach(([key, value]) => {
  console.log(key); // 'one'
  console.log(value); // 1
});
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay