为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUWWW 2022-12-22 13:46:45
我这里有一组对象: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 删除重复项,但我还没有看到任何我想在不使用太多循环的情况下以雄辩的方式完成的事情。我一直在思考如何最好地完成这一天,但没有找到任何帮助,我们将不胜感激
查看完整描述

3 回答

?
蛊毒传说

TA贡献1895条经验 获得超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);


查看完整回答
反对 回复 2022-12-22
?
MM们

TA贡献1886条经验 获得超2个赞

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


查看完整回答
反对 回复 2022-12-22
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

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



查看完整回答
反对 回复 2022-12-22
  • 3 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号