[英]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.