[英]Merge array of objects by nested property ID
这是我的例子:
{
id: 'productId',
label: 'productLabel',
items: productSizes.map( productSize => {
return {
id: productSize.groupId,
label: productSize.groupId.split('-')[0],
items: productSize.size,
}
}),
}
这将导致我们的数据如下所示:
{
id: 'productId',
label: 'productLabel'
items: [
{id: 'productA-11', label: 'productA', items: {width: 100, height: 100}},
{id: 'productA-11', label: 'productA', items: {width: 150, height: 150}},
{id: 'productA-11', label: 'productA', items: {width: 200, height: 200}},
{id: 'productB-22', label: 'productB', items: {width: 100, height: 100}},
]
}
但我想得到这样的东西:
{
id: 'productId',
label: 'productLabel'
items: [
{id: 'productA-11', label: 'productA', items: [ {width: 100, height: 100}, {width: 150, height: 150}, {width: 200, height:200}],
{id: 'productB-22', label: 'productB', items: [{width: 100, height: 100}],
]
}
不确定我是否用文字很好地描述了我的问题,但我想以某种方式展平内部属性items
,以便将 SAME productId
的大小合并到一个数组中。
Array.reduce
会帮助你
逻辑
items
数组。id
和label
相同的itemid
和label
的节点,将当前项目推送到该节点的items
数组,否则将一个新节点插入到具有id
、 label
和items
的累加器中工作小提琴
const data = { id: 'productId', label: 'productLabel', items: [ { id: 'productA-11', label: 'productA', items: { width: 100, height: 100 } }, { id: 'productA-11', label: 'productA', items: { width: 150, height: 150 } }, { id: 'productA-11', label: 'productA', items: { width: 200, height: 200 } }, { id: 'productB-22', label: 'productB', items: { width: 100, height: 100 } }, ] }; const { id, label } = data; const items = data.items.reduce((acc, curr) => { const node = acc.find(item => item.id === curr.id && item.label === curr.label); if (node) { node.items.push(curr.items); } else { acc.push({ id: curr.id, label: curr.label, items: [curr.items] }) } return acc; }, []) const output = { id, label, items, } console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.