我有一些看起来像这样的对象
var array = [
{car : {id:123}, count: 2, rule: {id:55, color: "red"}},
{car : {id:456}, count: 5, rule: {id:15, color: "blue"}},
{car : {id:883}, count: 1, rule: {id:557, color: "green"}}
...
];
Array是对象数组,car是具有id的对象,rule是具有id和颜色的对象。
我想遍历数组并创建一个看起来像这样的新数组
var newArray = [
{carId : 123, count:2, ruleId:55},
{carId : 456, count:5, ruleId:15},
{carId : 883, count:1, ruleId:557}
]
所以我想从对象数组中对象内部的对象中提取值。
如果可能,我希望使用ES5或ES6,使用Array.map或Array.forEach。
答案 0 :(得分:0)
您可以通过map()创建一个新数组来完成此操作,然后使用当前对象的属性在每次迭代中创建一个新对象。
var array = [{
car: {
id: 123
},
count: 2,
rule: {
id: 55,
color: "red"
}
}, {
car: {
id: 456
},
count: 5,
rule: {
id: 15,
color: "blue"
}
}, {
car: {
id: 883
},
count: 1,
rule: {
id: 557,
color: "green"
}
}];
var newArray = array.map(function(obj) {
return {
carId: obj['car']['id'],
count: obj['count'],
ruleId: obj['rule']['id']
};
});
console.log(newArray);

答案 1 :(得分:0)
使用地图,您可以轻松获得您的期望:
var array = [
{car : {id:123}, count: 2, rule: {id:55, color: "red"}},
{car : {id:456}, count: 5, rule: {id:15, color: "blue"}},
{car : {id:883}, count: 1, rule: {id:557, color: "green"}}
];
var newArray = array.map(x => ({carId: x.car.id, count: x.count, ruleId: x.rule.id})) ;
console.log(newArray);