数组对象相同属性的相加
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"}, ]; let obj = {}; let peon = person.reduce((cur,next) => { obj[next.id] ? "" : obj[next.id] = true && cur.push(next); return cur; },[]) //设置cur默认类型为数组,并且初始值为空的数组 console.log(peon); //2 Set去重,针对纯数组元素 let arr = [1,2,2]; console.log([...new Set(arr)]); // [1,2]