How might I extract the property values of a JavaS

2020-01-24 02:32发布

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

12条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-24 03:20

Using underscore:

var dataArray = _.values(dataObject);
查看更多
三岁会撩人
3楼-- · 2020-01-24 03:22
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
查看更多
聊天终结者
4楼-- · 2020-01-24 03:26
var dataArray = [];
for(var o in dataObject) {
    dataArray.push(dataObject[o]);
}
查看更多
再贱就再见
5楼-- · 2020-01-24 03:29

With jQuery, you can do it like this -

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

Demo

查看更多
▲ chillily
6楼-- · 2020-01-24 03:29

[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"}]
查看更多
虎瘦雄心在
7楼-- · 2020-01-24 03:36

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;
    }
}
查看更多
登录 后发表回答