Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  83] [ 3]  / answers: 1 / hits: 123092  / 10 Years ago, sat, august 9, 2014, 12:00:00

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.


More From » arrays

 Answers
11

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.


[#69849] Thursday, August 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
naomim

Total Points: 344
Total Questions: 95
Total Answers: 114

Location: Wales
Member since Mon, May 17, 2021
3 Years ago
;