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:11

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]]);
}
查看更多
劫难
3楼-- · 2020-01-24 03:13

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.

查看更多
地球回转人心会变
4楼-- · 2020-01-24 03:14

ES6 version:

var dataArray = Object.keys(dataObject).map(val => dataObject[val]);
查看更多
男人必须洒脱
5楼-- · 2020-01-24 03:14

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

查看更多
Root(大扎)
6楼-- · 2020-01-24 03:16

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楼-- · 2020-01-24 03:16

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

enter image description here

查看更多
登录 后发表回答