js根据对象数组中某⼀属性值,合并相同项,并对某⼀属性累加
处理
js根据对象数组中某⼀属性值,合并相同项,并对某⼀属性累加处理
Example: 根据code合并数组,并将sl值累加,如下两种⽅法:
let data = [{ code: 1001, name: '苹果', sl: 11 },
{ code: 1001, name: '苹果', sl: 11 },
{ code: 1001, name: '苹果', sl: 11 },
{ code: 1001, name: '苹果', sl: 11 },
{ code: 1002, name: '西⽠', sl: 11 },
{ code: 1002, name: '西⽠', sl: 15 },
{ code: 1003, name: '梨', sl: 15 },
js合并两个数组
{ code: 1003, name: '梨', sl: 15 }]
第⼀种:根据对象key的唯⼀性,累加sl值
let item = {}
for (let i = 0; i < data.length; i++) {
 item[data[i].code] = ~~item[data[i].code] + data[i].sl
}
console.log(item)
// 结果: {1001: 44, 1002: 26, 1003: 30}
第⼆种:根据reduce遍历累加,得到数组
let newArray = duce((total, cur, index) => {
  let hasValue = total.findIndex(current => { de === de})
  hasValue === -1 && total.push(cur)
  hasValue !== -1 && (total[hasValue].sl = total[hasValue].sl + cur.sl)
  return total
}, [])
console.log(newArray)
// 结果: [{code: 1001, name: "苹果", sl: 44}, {code: 1002, name: "西⽠", sl: 26}, {code: 1003, name: "梨", sl: 30}]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。