【发布时间】:2020-10-25 20:39:58
【问题描述】:
我正在尝试将对象数组转换为如下形式:
const categories = [{
"category": "Category 1",
"desc": "Description 1 of the category 1"
},
{
"category": "Category 1",
"desc": "Description 2 of the category 1"
}, {
"category": "Category 2",
"desc": "Description 1 of the category 2"
},
{
"category": "Category 2",
"desc": "Description 2 of the category 2"
},
{
"category": "Category 3",
"desc": "Description 1 of the category 3"
}, {
"category": "Category 3",
"desc": "Description 2 of the category 3"
}
];
到表单(期望的结果集);
[
{
"category": "Category 1",
"desriptionList": [
{
"desc": "Description 1 of the category 1"
},
{
"desc": "Description 2 of the category 1"
}
]
},
{
"category": "Category 2",
"desriptionList": [
{
"error": "Description 1 of the category 2"
},
{
"error": "Description 2 of the category 2"
},
]
},
{
"category": "Category 3",
"desriptionList": [
{
"error": "Description 1 of the category 3"
},
{
"error": "Description 2 of the category 3"
},
]
}
]
使用reduce 方法:
const result = categories.reduce((acc, item) => {
return [{
...acc,
'category': item.category,
'desriptionList': item.desc
}]
}, [])
但我似乎以错误的方式在错误的地方使用了累加器,因为输出很奇怪;
[{
0: {
0: { ... },
category: "Category 3",
desriptionList: "Description 1 of the category 3"
},
category: "Category 3",
desriptionList: "Description 2 of the category 3"
}]
【问题讨论】:
标签: javascript arrays arraylist ecmascript-6