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"}]
This question is related to
javascript
arrays
json
[It turns out my answer is similar to @Anonymous, but I keep my answer here since it explains how I got my answer].
The original object has THREE properties (i.e. 3 keys and 3 values). This suggest we should be using Object.keys()
to transform it to an array with 3 values.
var dataArray = Object.keys(dataObject);
// Gives: ["object1", "object2", "object3" ]
We now have 3 values, but not the 3 values we're after. So, this suggest we should use Array.prototype.map()
.
var dataArray = Object.keys(dataObject).map(function(e) { return dataObject[e]; } );
// Gives: [{"id":1,"name":"Fred"},{"id":2,"name":"Wilma"},{"id":3,"name":"Pebbles"}]
Maybe a bit verbose, but robust and fast
var result = [];
var keys = Object.keys(myObject);
for (var i = 0, len = keys.length; i < len; i++) {
result.push(myObject[keys[i]]);
}
Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:
if(Object.values == null) {
Object.values = function(obj) {
var arr, o;
arr = new Array();
for(o in obj) { arr.push(obj[o]); }
return arr;
}
}
Using underscore:
var dataArray = _.values(dataObject);
Assuming your dataObject is defined the way you specified, you do this:
var dataArray = [];
for (var key in dataObject)
dataArray.push(dataObject[key]);
And end up having dataArray populated with inner objects.
With jQuery, you can do it like this -
var dataArray = $.map(dataObject,function(v){
return v;
});
Object.values() method is now supported. This will give you an array of values of an object.
Object.values(dataObject)
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
ES6 version:
var dataArray = Object.keys(dataObject).map(val => dataObject[val]);
This one worked for me
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
ES2017 using Object.values
:
const dataObject = {_x000D_
object1: {_x000D_
id: 1,_x000D_
name: "Fred"_x000D_
},_x000D_
object2: {_x000D_
id: 2,_x000D_
name: "Wilma"_x000D_
},_x000D_
object3: {_x000D_
id: 3,_x000D_
name: "Pebbles"_x000D_
}_x000D_
};_x000D_
_x000D_
const valuesOnly = Object.values(dataObject);_x000D_
_x000D_
console.log(valuesOnly)
_x000D_
I prefer to destruct object values into array:
[...Object.values(dataObject)]
var dataObject = {
object1: {id: 1, name: "Fred"},
object2: {id: 2, name: "Wilma"},
object3: {id: 3, name: "Pebbles"}
};
var dataArray = [...Object.values(dataObject)];
Source: Stackoverflow.com