簡體   English   中英

按嵌套屬性 ID 合並對象數組

[英]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會幫助你

邏輯

  • 遍歷 object 的items數組。
  • 檢查reducer的累加器是否已經有一個idlabel相同的item
  • 如果有一個具有相同idlabel的節點,將當前項目推送到該節點的items數組,否則將一個新節點插入到具有idlabelitems的累加器中

工作小提琴

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM