A blog for technology, SEO tips, website development and open source programming.

How to convert an object to an array of objects in Javascript?

0 832

You may be asking why, the answer is actually quite simple. In programming we are not always in control of the format in which our data is delivered to us. With this in mind it becomes important to understand how to convert our data into our desired format. Check out, How to convert an object to an array of objects in Javascript?




Example

Using newer Javascript features there is an easy one liner that can achieve this result using Object.values().

const profileObj = {
  first: 'Panayiotis',
  last: 'Georgiou',
  links: {
      twitter: 'https://twitter.com/panay_georgiou',
      facebook: 'https://facebook.com/panayiotisgeorgiou.net',
      cv: 'https://www.panayiotisgeorgiou.com',
      blog: 'http://www.panayiotisgeorgiou.net',
    }
  };

const profileArray = Object.values(profileObj);

You can use this if you are using babel but if not I will show you below how you can do this in a more widely supported manner with Object.keys().

const profileArray = Object.keys(profileObj).map(i =>profileObj[i])

This second method is quite well supported. Check out both Object Values and Object Keys MDN documentation to learn where you may have issues with support and for more info on these features.

As a note, if you prefer a key valued pair check out Object Entries.

That’s it for now.

If you liked this article, then please subscribe to my YouTube Channel for video tutorials.

You can also find me on Twitter and Facebook.

[alert type=yellow ] Don’t miss out ..

Destructuring JavaScript Objects

Arrow Functions for Beginners Javascript

[/alert]

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More