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.
To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() .
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.
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.
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.
just use Object.values
Object.values(inputObj); // => ['foo', [1,2,3], null, 55]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With