JSON 多字段相同时如何合并求和?

当 name 和 type 同时相同的情况下 value 相加合并

[
    {
        name:'A',
        value:10,
        type:'Z'
    },
    {
        name:'A',
        value:5,
        type:'Z'
    },
    {
        name:'B',
        value:3,
        type:'S'
    },
    {
        name:'B',
        value:2,
        type:'S'
    },
    {
        name:'C',
        value:10,
        type:'Z'
    },
    {
        name:'C',
        value:12,
        type:'E'
    }
]

期望结果

[
    {
        name:'A',
        value:15,
        type:'Z'
    },
    {
        name:'B',
        value:5,
        type:'S'
    },
    {
        name:'C',
        value:10,
        type:'Z'
    },
    {
        name:'C',
        value:12,
        type:'E'
    },
]
阅读 2.6k
4 个回答

reduce解决吧

function sumArr (arr) {
    return JSON.parse(JSON.stringify(arr)).reduce((newArr, item) => {
        const selectItem = newArr.find(_item => _item.name === item.name && _item.type === item.type)
        if (selectItem) {
            selectItem.value += item.value
        } else {
            newArr.push(item)
        }
        return newArr
    }, [])
}

经提醒,已修复改变原数组bug

let obj = {}
let list = arr.reduce((list, item) => {
    let key = item.name + item.type
    if(!obj[key]){
        list.push(obj[key] = {...item})
    }else{
        obj[key].value += item.value
    }
    return list
}, [])

单层循环

const sumValue = (arr) => {
  const obj = {};
  arr.forEach(el => {
    let key = `${el.name}_${el.type}`;
    if(!obj[key]){
      obj[key] = {...el};
    }else{
      obj[key].value += el.value;
    }
  });
  return Object.values(obj);
};
let arr = list.reduce((s, v) => {
  let index = s.findIndex(it => v.name === it.name && v.type === it.type)
  index !== -1 ? (s[index].value+=v.value) : s.push({...v})
  return s
}, [])
console.log(arr)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏