【问题标题】:Merge array of objects by nested property ID按嵌套属性 ID 合并对象数组
【发布时间】:2021-12-28 05:32:34
【问题描述】:

这是我的例子:

{
    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 的大小合并到一个数组中。

【问题讨论】:

  • 到目前为止,您尝试过什么合并它们?你被困在哪里了?请发布您尝试过的代码,以便有人检查并帮助您解决问题。
  • @Nitheesh 我没有代码,因为我不知道如何着手解决这个问题。

标签: javascript arrays ecmascript-6


【解决方案1】:

Array.reduce 会帮助你

逻辑

  • 循环遍历对象的items 数组。
  • 检查reducer的累加器是否已经有idlabel相同的item
  • 如果有一个具有相同idlabel 的节点,则将当前项推送到该节点的items 数组,否则将一个新节点插入到具有idlabel 和@987654330 的累加器中@

工作小提琴

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);

【讨论】:

  • 谢谢 Nitheesh,它有效。我想过array.reduce(),但从来没有真正理解过。
猜你喜欢
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 2015-12-05
  • 1970-01-01
  • 2012-12-01
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多