javascript - 转换 javascript 对象
问题描述
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()
or.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; }
推荐阅读
- parameters - 直接放入未执行时,参数获取值
- r - 在特定的 ggplots 中添加一个百分比符号来标记,而不是在其他图中
- php - 活动菜单不保持活动状态并突出显示
- c++ - 制作指向结构数组的指针
- c# - 有谁知道如何修复:System.ComponentModel.Win32Exception:'系统找不到指定的文件'来自 Visual Studio?
- javascript - 我一直在尝试通过用户输入使用 for 循环,但由于某种原因它既不显示错误也不显示输出
- loops - 当使用 while 循环输入负数时,停止接收 Arraylist 的用户输入
- java - Authenticator#requestPasswordAuthentication 的用例
- flutter - 我有一个表单,其中有两个文本输入。当用户在一个输入中输入文本并转到另一个时,文本消失了。该怎么办?
- python - get secrets from enterprise vault using python