繁体   English   中英

在 Javascript 上合并具有相同 ID 的 object 数组中的项目

[英]Merge item in array of object with the same ID on Javascript

这是 object 的样子:

 let data = [ { brandId: '12345', brand: 'Adidas', item: { name: 'Adidas 1', price: '200', }, }, { brandId: '12345', brand: 'Adidas', item: { name: 'Adidas 2', price: '230', }, }, { brandId: '7878', brand: 'Nike', item: { name: 'Nike 1', price: '305', }, } ];

如果 object 具有相同的brandID ,我希望item object 将合并:

 let data = [ { brandId: '12345', brand: 'Adidas', item: [ { name: 'Adidas 1', price: '200', }, { name: 'Adidas 2', price: '230', }, ], }, { brandId: '7878', brand: 'Nike', item: { name: 'Nike 2', price: '316', }, }, ];

是否有任何 javascript 语法或方法来执行此操作? 并有解释会很好,谢谢

(假设你的 output 只是一个拼写错误,名称/价格实际上并没有改变)你可以使用array reduce

let data = [
  {
    brandId: '12345',
    brand: 'Adidas',
    item: {
      name: 'Adidas 1',
      price: '200',
    },
  },
  {
    brandId: '12345',
    brand: 'Adidas',
    item: {
      name: 'Adidas 2',
      price: '230',
    },
  },
  {
    brandId: '7878',
    brand: 'Nike',
    item: {
      name: 'Nike 1',
      price: '305',
    },
  }
];

const mergedItems = data.reduce((acc, curr) => {
  // check if current exist on the accumulator
  const exist = acc.find(brand => brand.brandId === curr.brandId);

  // if it does, add the item on it
  if (exist) {
    return acc.map((brand) => {
      if (brand.brandId === exist.brandId) {
        return {
           ...brand,
           item: brand.item.concat(curr.item),
        }
      }
    })
  }

  // if it doesnt, add it on accumulator, and make the item array
  return acc.concat({
    ...curr,
    item: [
      curr.item 
   ]
  })
})

(我手动写了代码,没有测试)

您可以使用Map简单地实现此结果

 let data = [ { brandId: "12345", brand: "Adidas", item: { name: "Adidas 1", price: "200", }, }, { brandId: "12345", brand: "Adidas", item: { name: "Adidas 2", price: "230", }, }, { brandId: "7878", brand: "Nike", item: { name: "Nike 1", price: "305", }, }, ]; const dict = new Map(); data.forEach((o) => { dict.get(o.brandId)? dict.get(o.brandId).item.push(o.item): dict.set(o.brandId, {...o, item: [o.item] }); }); const result = []; for (let [k, v] of dict) { v.item.length === 1? result.push({...v, item: v.item[0] }): result.push(v); } console.log(result);
 /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */.as-console-wrapper { max-height: 100%;important: top; 0; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM