JavaScript 对象的这种简单(和以前一样,我认为)转换让我失败了。我想用以下方式压平这个对象。
这就是我所拥有的:
{
"1": {
"group": "Clothes",
"brand": {
"0": {
"brand_id": "12",
"brand_name": "Adidas"
},
"1": {
"brand_id": "15",
"brand_name": "Zara"
}
}
},
"2": {
"group": "Cars",
"brand": {
"0": {
"brand_id": "43",
"brand_name": "Ferrari"
},
"1": {
"brand_id": "51",
"brand_name": "BMW"
}
}
}
}
这就是我想要得到的
{0: {
brand_id: "12",
brand_name: "Adidas",
group: "Clothes",
}
1: {
brand_id: "15",
brand_name: "Zara",
group: "Clothes",
},
2: {
brand_id: "43",
brand_name: "Ferrari",
group: "Cars",
}
3: {
brand_id: "51",
brand_name: "BMW",
group: "Cars",
}}
我尝试使用 .reduce()
或 .map()
但效果不佳。
最佳答案
你可以这样做:
const data = {1: {group: 'Clothes',brand: [{0: {brand_id: '12',brand_name: 'Adidas'}},{1: {brand_id: '15',brand_name: 'Zara'}}]},2: {group: 'Cars',brand: [{0: {brand_id: '43',brand_name: 'Ferrari'}},{1: {brand_id: '51',brand_name: 'BMW'}}]}};
const result = {};
Object.keys(data).forEach(k => {
data[k].brand.forEach((b, i) => {
result[Object.keys(result).length] = {
brand_id: b[i].brand_id,
brand_name: b[i].brand_name,
group: data[k].group
};
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 转换 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53113837/