原生JS关于数组对象相同属性的相加与数组去重

2022-07-13 16:45:54 浏览数 (1)

数组对象相同属性的相加

let obj = {}; const arr = [ { name: ‘A’, stock: 1 }, { name: ‘B’, stock: 1 }, { name: ‘A’, stock: 33 }, { name: ‘B’, stock: 2 }, { name: ‘C’, stock: 0 } ]; // 第一种方式 arr.forEach(v => obj[v.name] = obj[v.name] === undefined ? v.stock : obj[v.name] v.stock) console.log(obj) // 第二种方法 arr.forEach(v=>{ if (obj.hasOwnProperty(v.name)) { obj[v.name] = v.stock } else{ obj [v.name] = v.stock } }) console.log(obj)

数组去重

//1 reduce去重,针对数组对象 let person = [ {id: 0, name: “A”}, {id: 1, name: “B”}, {id: 2, name: “C”}, {id: 3, name: “D”}, {id: 1, name: “E”}, {id: 2, name: “F”},

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120055440

0 人点赞