views:

89

answers:

2

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"}]
+3  A: 
var dataArray = new Array;
for(var o in dataObject) {
    dataArray.push(dataObject[o]);
}
Murali VP
I assume that he wants to preserve the ordering, so this isn't good enough.
SLaks
And what is "ordering" in your opinion?
Marko Dumic
If you don't want to include properties from the object's prototype (there *shouldn't* be any if it's a plain object), you can filter them by checking `dataObject.hasOwnProperty(o)`.
Matthew Crumley
A: 

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.

Marko Dumic
This also doesn't do what he's asking for.
SLaks
Please, point me to what it doesn't do that he was asking?
Marko Dumic
He wants the objects themselves, not their names.
SLaks
In that case, just omit the ".name" in the third line.
Marko Dumic