Given a JavaScript object:
var dataObject = { object1: {id: 1, name: "Fred"}, object2: {id: 2, name: "Wilma"}, object3: {id: 3, name: "Pebbles"} };
How do I efficiently extract the inner objects into an array? I do not need to maintain a handle on the object[n] IDs.
var dataArray = [ {id: 1, name: "Fred"}, {id: 2, name: "Wilma"}, {id: 3, name: "Pebbles"}]
To convert an object into an array in Javascript, you can use different types of methods. Some of the methods are Object. keys(), Object. values(),and Object.
You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.
To get the values of an object as an array, use the Object. values() method, passing it the object as a parameter. The method returns an array containing the object's property values in the same order as provided by a for ... in loop. Copied!
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
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