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.
Solution 1:
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.
Solution 2:
just use Object.values
Object.values(inputObj); // => ['foo', [1,2,3], null, 55]
Solution 3:
I like the old school way:
var i=0, arr=[];
for (var ob in inputObj)
arr[i++]=ob;
Old school wins the jsperf test by a large margin, if not the upvotes. Sometimes new additions are "mis-features."
Solution 4:
This can be achieved using the Array Comprehension syntax:
[for (key of Object.keys(inputObj)) inputObj[key]]
Usage example:
var inputObj = {a:'foo', b:[1,2,3], c:null, z:55};
var arr = [for (key of Object.keys(inputObj)) inputObj[key]];
console.log(arr);
// prints [ 'foo', [ 1, 2, 3 ], null, 55 ]