请参阅我的Fiddle,其中包含以下所有代码。
如果之前已经回答过这个问题,我深表歉意。我在这里找到了关于按属性分组的类似问题,但我没有找到结果仍然是对象数组的示例。
我从这种数据格式开始:
const originalData = [
{
"groupId": 0,
"color": "red",
"shape": "circle"
},
{
"groupId": 1,
"color": "green",
"shape": "square"
},
{
"groupId": 1,
"color": "orange",
"shape": "hexagon"
},
{
"groupId": 1,
"color": "purple",
"shape": "triangle"
},
{
"groupId": 2,
"color": "aqua",
"shape": "diamond"
},
{
"groupId": 2,
"color": "blue",
"shape": "trapezoid"
}
];
我想把它转换成一个新的对象数组,按groupId
属性值分组:
const desiredData = [
{
"groupId": 0,
"items": [
{
"color": "red",
"shape": "circle"
}
]
},
{
"groupId": 1,
"items": [
{
"color": "green",
"shape": "square"
},
{
"color": "orange",
"shape": "hexagon"
},
{
"color": "purple",
"shape": "triangle"
}
]
},
{
"groupId": 2,
"items": [
{
"color": "aqua",
"shape": "diamond"
},
{
"color": "blue",
"shape": "trapezoid"
}
]
}
];
这个 reduce 函数(我在MDN 上找到的)是我最接近转换数据的函数。我在 Javascript 中转换数据的经验有限,我不确定如何group
在转换过程中添加字段(如)。此外,结果是一个对象,而不是一个对象数组。
const actualFormattedData = originalData.reduce((acc, obj) => {
let key = obj['groupId'];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
reduce 函数的输出:
{
"0": [
{
"groupId": 0,
"color": "red",
"shape": "circle"
}
],
"1": [
{
"groupId": 1,
"color": "green",
"shape": "square"
},
{
"groupId": 1,
"color": "orange",
"shape": "hexagon"
},
{
"groupId": 1,
"color": "purple",
"shape": "triangle"
}
],
"2": [
{
"groupId": 2,
"color": "aqua",
"shape": "diamond"
},
{
"groupId": 2,
"color": "blue",
"shape": "trapezoid"
}
]
}
最终目标是在 React 中映射对象数组。我知道我可以使用Object.entries
和 数组索引来实现与actualFormattedData
原样类似的结果,但如果我能首先使actualFormattedData
看起来完全像desiredData
.