猿问

如何首先组合对象的属性,然后使用 Javascript 删除对象数组中的重复项

我这里有一组对象:


const arr = [

  { id: 1, name: "test1", quantity:1 },

  { id: 2, name: "test2", quantity:1 },

  { id: 2, name: "test3", quantity:1 },

  { id: 3, name: "test4", quantity:1 },

  { id: 4, name: "test5", quantity:1 },

  { id: 5, name: "test6", quantity:1 },

  { id: 5, name: "test7", quantity:1 },

  { id: 6, name: "test8", quantity:1 }

];

我想在删除它们之前将大量重复对象加在一起


所以结果是:


const arr = [

  { id: 1, name: "test1", quantity:1 },

  { id: 2, name: "test3", quantity:2 },

  { id: 3, name: "test4", quantity:1 },

  { id: 4, name: "test5", quantity:1 },

  { id: 5, name: "test6", quantity:2 },

  { id: 6, name: "test8", quantity:1 }

];

我已经看到它的变体使用 map 或 reduce 删除重复项,但我还没有看到任何我想在不使用太多循环的情况下以雄辩的方式完成的事情。


我一直在思考如何最好地完成这一天,但没有找到任何帮助,我们将不胜感激


HUWWW
浏览 125回答 3
3回答

蛊毒传说

您可以将 reduce 与对象一起使用,以存储具有每个 id 的元素。const arr = [  { id: 1, name: "test1", quantity:1 },  { id: 2, name: "test2", quantity:1 },  { id: 2, name: "test3", quantity:1 },  { id: 3, name: "test4", quantity:1 },  { id: 4, name: "test5", quantity:1 },  { id: 5, name: "test6", quantity:1 },  { id: 5, name: "test7", quantity:1 },  { id: 6, name: "test8", quantity:1 }];const res = Object.values(  arr.reduce((acc,curr)=>{  acc[curr.id] = acc[curr.id] || {...curr, quantity: 0};  acc[curr.id].quantity += curr.quantity;  return acc;  }, {}));console.log(res);

MM们

const arr = [    { id: 1, name: "test1", quantity: 1 },    { id: 2, name: "test2", quantity: 1 },    { id: 2, name: "test3", quantity: 1 },    { id: 3, name: "test4", quantity: 1 },    { id: 4, name: "test5", quantity: 1 },    { id: 5, name: "test6", quantity: 1 },    { id: 5, name: "test7", quantity: 1 },    { id: 6, name: "test8", quantity: 1 }];var result = arr.reduce(function (r, a) {    r[a.id] = r[a.id] || { id: a.id, quantity: 0, name: a.name };    r[a.id].quantity += a.quantity;    return r;}, Object.create(null));console.log(JSON.stringify(result));

有只小跳蛙

使用forEach具有聚合数量计数的循环和构建对象。const convert = (arr) => {  const res = {};  arr.forEach(({ id, ...rest }) =>    res[id] ? (res[id].quantity += 1) : (res[id] = { id, ...rest })  );  return Object.values(res);};const arr = [  { id: 1, name: "test1", quantity: 1 },  { id: 2, name: "test2", quantity: 1 },  { id: 2, name: "test3", quantity: 1 },  { id: 3, name: "test4", quantity: 1 },  { id: 4, name: "test5", quantity: 1 },  { id: 5, name: "test6", quantity: 1 },  { id: 5, name: "test7", quantity: 1 },  { id: 6, name: "test8", quantity: 1 },];console.log(convert(arr));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答