DEV Community

loading...

Converting Object to an Array in JavaScript

samanthaming profile image Samantha Ming Originally published at samanthaming.com ・3 min read

CodeTidbit by SamanthaMing.com

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

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 πŸ₯³

const zoo = {
  lion: '🦁',
  panda: '🐼'
};

Object.keys(zoo)
// ['lion', 'panda']

Object.values(zoo)
// ['🦁', '🐼']

Object.entries(zoo)
// [ ['lion', '🦁'], ['panda', '🐼'] ]

Time for a story...

Ancient times

Long long ago, in a far far galaxy, looping over Objects was not so easy. Okay, I'm exaggerating a bit πŸ˜…. But I remember whenever I needed to convert an object into an array, I had to do something like this.

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

var keys = [];

for (var number in numbers) {
  if(numbers.hasOwnProperty(number)){
    keys.push(number)
  }
}

keys; // [ 'one', 'two' ]

I always was so annoy and wished there was a better way...

ES6 - Object.keys

And then ES6 happened! My life changed! We finally have an easier way πŸ₯³

Now, there was a built-in method that quickly turns all the keys in my object into an array:

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

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

Life was beautiful! But then I became angry again. Why can I only extract the keys, I want my values too! Humans always want more don't we πŸ˜‚ And then ES2017 rolled in...

Object.values

Hi, I'm ES2017 and I grant you all your wish πŸ§žβ€β™€οΈ. you can now easily extract the values into an array with one method.

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

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

Object.entries

But ES2017 didn't stop there. It gave me more! I grant you BOTH keys and values now, so stop being angry. I was blown away. It turned my frown upside down πŸ˜†

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

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

Booya πŸ‘Š

Object.entries + Destructuring

But then I'm like...nested array 🀨. C'mon, that's not fun to work with. ES6 swoops in and like, don't worry! That's why I gave you destructuring!

const numbers = {
  one: 1,
}

const objectArray = Object.entries(numbers);

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

ES6, that's why you are simply the best πŸ’›

End of story

Hope you enjoyed my code story-telling time πŸ˜‚

Now go out there and have some fun with all these amazing Object methods 😊

Browser Support

Object.keys has the best support. When I say best, it means it supports Internet Explorer πŸ˜†. The other, Object.values and Object.entries, unfortunately, don't support Internet Explorer. Luckily, polyfill exists which can improve support.

Polyfill

But wait, there's more...

Your next question might be, now how do I convert the array back to an object. Don't worry, that's covered. There is a new method called Object.fromEntries. It essentially is the opposite of Object.entries.

const array = [
  [ 'one', 1 ],
  [ 'two', 2 ]
];

Object.fromEntries(array);
// { one: 1, two: 2 }

MDN: Object.fromEntries

Note: This is extremely new, so support will be limited. Keep this in your knowledge box, but maybe wait a bit longer before you put it in your actual toolbox 🧰

Community Input

  • @podfeet: I wanted to create an object in a specific form, so I used object.keys to discover the indices of the specific elements I wanted to extract.

Resources

β€”

Thanks for reading ❀
Say Hello! Instagram | Twitter | Facebook | Blog | SamanthaMing.com

Discussion (14)

pic
Editor guide
Collapse
aminnairi profile image
Amin

Hi there, great article! I think, in my personal use case as a web developer doing most of my work in the front-end, a common use would be to use a tool like qs to turn an URI query into an object like ?b=foo&a=bar to {b: "foo", a: "bar"}, use Object.entries to turn it into an array, use Array.sort and feed it a closure to sort my queries by keys and turn it back into an object with Object.fromEntries and use qs to stringify it back. This can be cool to prevent having multiple variation of a URI query that leads to the same page (prevention of duplicate content). Without ES2015+ I think this would be such a tedious task to do but now we can do things that seemed hard back then so easy now.

Collapse
samanthaming profile image
Samantha Ming Author

Whoa! That’s a terrific example! Thanks for sharing πŸ‘πŸ‘ ES6 and beyond is make it so much easier for us JS developers πŸ™Œ

Collapse
fetishlace profile image
fetishlace

Hi there:-) I have to google qs, to read it is node query string parser, since not into node yet:-) But if it is about sorting query string, there is build-in sort method in vanilla js URLSearchParams, it is iterable, so you can also get entries from it, you can has/set/get/append/delete/sort. Not sure for what all is qs needed for, it seems to me like abstract of URL Object possibilities + some other vanilla just wrapped into functions.

const url = new URL(location);
const params = url.searchParams;
const entries = [...params.entries()];
params.sort();
const entriesSorted = [...params.entries()];

Collapse
aminnairi profile image
Amin

Worth noting that this is available in Node 13.1.0 so quite new for the moment in the server side. User of earlier versions will want to stick to QS.

Thread Thread
fetishlace profile image
fetishlace • Edited

Thanks for feedback, that makes sense, I know practically nothing about node, just proposed it because thought it is older ECMA and implemented in all V8 based things.
I were searching a bit and found thread (stackoverflow.com/questions/472665...) stating that "Node v10 has built-in availability of URLSearchParams on the global object" but haven't tested, also that qs has sorting function build-in it seems.
Anyway I would go for that vanilla URL object with its possibilities now after all the search since I do not see any added value to that native URL API - sure it can have some value (i mean libraries) when it is about back-compatibility and browsers - i see IE don't know URLSearchParams, but not much surprising :-)

Thread Thread
aminnairi profile image
Amin

Yes whenever possible we should thrive to use the built in ECMAScript way of doing things you are right. And you are also right I have mistakenly taken the latest version but it is not used in production in express servers because (at least for us in enterprise) we are using custom delimiters and special encoder for our queries which makes URLSearchParams difficult to use alone. But I would use it in any other cases.

Thread Thread
fetishlace profile image
fetishlace

Thanks for explain! ;-) I am going to learn node soon anyway, since I need backend for some of my projects. I am just a bit frightened from number of libraries, packages, modules... I've just started some months ago and I am still just a hobby coder but I really like many things late ECMA brings into JS and I am really vanilla js fan - sometimes there is some sound reasoning behind people using some library, sometimes I have seen there is no other reason than preference or that someone is used to it from the past (when some new ECMA tools did not exist), or just it is more efficient for the use case (and that could be totally different story with another use case) - so it is good to hear why and how professionals using it :-)

Thread Thread
aminnairi profile image
Amin

You'll pick Node really easy if you are that interested about the ECMAScript standard I'm sure. And yeah, even myself I tend to use libraries when there is now lots of things that the standard is already doing natively.

Thread Thread
fetishlace profile image
fetishlace

Thanks for discussion and some encouragement:-) I will try to befriend Node as soon as possible since ye I have to admit i am postponing it for some time. I am aware on the other hand that some shiny new ECMA features not implemented the best at the time (so some runtimes way better for old ways of doing the same, and compatibility issues...) but it is changing with a time and lot of it is pretty good for doing a lot with a little - what is what you need for prototyping and efficient and fast building of things in general i guess. Good luck with your work too:-)

Collapse
fetishlace profile image
fetishlace

Cool written! I can really feel with this cute fairy-tale with good mood emoticons, it even move me to register to like <3

Collapse
samanthaming profile image
Samantha Ming Author

Woohoo! Glad it registers with you πŸ˜† I definitely found this to be more fun to write. I will try this style with more future posts as well! Thanks for the positive feedback 😁

Collapse
jacobmgevans profile image
Jacob Evans

I wrote an article about similar topic recently. I liked some of your explanations better πŸ˜†πŸ™‚
Dev.to/jacobmgevans

Collapse
anjankant profile image
Anjan Kant

thanks!! it's very helpful

Collapse
samanthaming profile image
Samantha Ming Author

Awesome! Glad you found it helpful 😊