[英]how to get all object that has the same id in array?
I have an array of objects and I want to re-shape them based on a similar id "itemId"我有一个对象数组,我想根据类似的 id“itemId”重新塑造它们
array = [
{"choicesId": 2, "itemId": 40, "optionChoicesId": 4},
{"choicesId": 11, "itemId": 40, "optionChoicesId": 14},
{"choicesId": 141, "itemId": 41, "optionChoicesId": 104},
{"choicesId": 311, "itemId": 41, "optionChoicesId": 1987}
];
expected array预期数组
[
{"id":40,"selected_ids":[{"choicesId":2},{"choicesId":11}]},
{"id":41,"selected_ids":[{"choicesId":141},{"choicesId":311}]},
...
]
An easy approach can be like this一个简单的方法可以是这样的
const mergeSelections = (selections) => {
const groupedSelections = selections.reduce((acc, selection) => {
const { itemId, choicesId } = selection;
if (!acc[itemId]) {
acc[itemId] = { id: itemId, selected_ids: [] };
}
acc[itemId].selected_ids.push({ choicesId });
return acc;
}, {});
return Object.values(groupedSelections);
};
const array = [
{ choicesId: 2, itemId: 40, optionChoicesId: 4 },
{ choicesId: 11, itemId: 40, optionChoicesId: 14 },
{ choicesId: 141, itemId: 41, optionChoicesId: 104 },
{ choicesId: 311, itemId: 41, optionChoicesId: 1987 },
];
console.log(mergeSelections(array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.