Skip to main content

Command Palette

Search for a command to run...

Converting Object to an Array in Javascript

What if you received an object of objects rather than array of objects from backend as a response?

Published
β€’1 min read
Converting Object to an Array in Javascript
M

I am a Full Stack Developer working on Next Generation Software, Web & Mobile Technologies since 8+ years. Have a look on my portfolio: https://linktr.ee/mawaisshaikh

  • I am Pakistan’s first AWS DevAx Mentor and an Auth0 Ambassador.
  • Community Member (Google Developer Groups).
  • Community Member (Angular).
  • An open-source contributor. πŸ’»
  • Tech speaker. 🎀
  • Mentor. πŸš€

I have spoken at multiple international community events including google developer groups like #gdgSoweto, #AngularDutch, #ngKolachi as well πŸ™Œ

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, after 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] ]

Object.entries + Destructuring

const numbers = {
  one: 1,
};

const objectArray = Object.entries(numbers);

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

good write. thanks