繁体   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