How might I extract the property values of a JavaS

2020-01-24 03:18发布

问题:

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"}]

回答1:

var dataArray = [];
for(var o in dataObject) {
    dataArray.push(dataObject[o]);
}


回答2:

var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});


回答3:

ES6 version:

var dataArray = Object.keys(dataObject).map(val => dataObject[val]);


回答4:

Using underscore:

var dataArray = _.values(dataObject);


回答5:

With jQuery, you can do it like this -

var dataArray = $.map(dataObject,function(v){
     return v;
});

Demo



回答6:

ES2017 using Object.values:

const dataObject = {
    object1: {
        id: 1,
        name: "Fred"
    },
    object2: {
        id: 2,
        name: "Wilma"
    },
    object3: {
        id: 3,
        name: "Pebbles"
    }
};

const valuesOnly = Object.values(dataObject);

console.log(valuesOnly)



回答7:

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.



回答8:

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;
    }
}


回答9:

[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"}]


回答10:

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]]);
}


回答11:

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



回答12:

In case you use d3. you can do d3.values(dataObject) which will give