我正在尝试将对象数组转换为如下形式:
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"
}]