js对数组的处理,怎么处理好,求解

名字不能缺
  • 144
var obj=[
        {name:'王',money:1},
        {name:'李',money:2},
        {name:'张',money:3},
        {name:'王',money:1},
        {name:'李',money:2},
        {name:'张',money:3},
        {name:'王',money:1},
        {name:'李',money:2},
        {name:'张',money:3},
    ]

怎么操作这个数组,使其name相同的项组合到一起,money相加
最终的结果这样

 var obj=[
        {name:'王',money:3},
        {name:'李',money:6},
        {name:'张',money:9},
     
    ]

name字段 王 李 赵 不是固定的,不能如此if(name=='王')之类的

回复
阅读 2.3k
4 个回答
止醉
  • 770
    let lists = [];
    let persons = obj.reduce(function(person, item) {
        if( person[item.name] ) {
            person[item.name].money += item.money;
        }
        else {
            person[item.name] = {name: item.name, money: item.money};
            lists.push(person[item.name]);
        }
        return person;
    },{});

    console.log(persons);
    console.log(lists);

输出一个persons.一个lists,看看你需要哪个结构

李引证
  • 3.9k
Array.from(obj.reduce((m,v)=>m.set(v.name,m.has(v.name)?m.get(v.name)+v.money:v.money),new Map),arr=>({name:arr[0],money:arr[1]}))
小皇帝James
  • 534
var obj=[
    {name:'王',money:1},
    {name:'李',money:2},
    {name:'张',money:3},
    {name:'王',money:1},
    {name:'李',money:2},
    {name:'张',money:3},
    {name:'王',money:1},
    {name:'李',money:2},
    {name:'张',money:3},
], _obj_ = {}, arr = [];
obj.forEach(function(value){
    if (_obj_[value.name]) {
        _obj_[value.name] += value.money;
    } else {
        _obj_[value.name] = value.money;
    }
});
for (var i in _obj_) {
    arr.push({name:i, money:_obj_[i]});
};

最后arr就是你要的,顺便说下你用obj命名Array的实例看的我好别扭!

 Object.entries(
     obj.reduce(
         (tmp, item) => (tmp[item.name] = ~~tmp[item.name] + item.money, tmp) ,
         {}
      )
 )
 .map(entry => ({name:entry[0], money:entry[1]}))
宣传栏