Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Object to Array using ES6 features

Given a javascript object, how can I convert it to an array in ECMAScript-6 ?

For example, given:

 var inputObj = {a:'foo', b:[1,2,3], c:null, z:55}; 

The expected output would be:

 ['foo', [1,2,3], null, 55] 

The order of the elements in the result is not important to me.

like image 753
urish Avatar asked Aug 09 '14 10:08

urish


People also ask

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() .

Can we convert object to array in JavaScript?

JavaScript Objects Convert object's values to array You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

How do you change an object to an array in react?

To update an object in an array in React state: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Update the object that satisfies the condition and return all other objects as is.


Video Answer


2 Answers

Use (ES5) Array::map over the keys with an arrow function (for short syntax only, not functionality):

let arr = Object.keys(obj).map((k) => obj[k]) 

True ES6 style would be to write a generator, and convert that iterable into an array:

function* values(obj) {     for (let prop of Object.keys(obj)) // own properties, you might use                                        // for (let prop in obj)         yield obj[prop]; } let arr = Array.from(values(obj)); 

Regrettably, no object iterator has made it into the ES6 natives.

like image 141
Bergi Avatar answered Sep 28 '22 04:09

Bergi


just use Object.values

Object.values(inputObj); // => ['foo', [1,2,3], null, 55] 
like image 37
Fareed Alnamrouti Avatar answered Sep 28 '22 06:09

Fareed Alnamrouti