Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

如何让多个对象相同的属性值相加

    var data = [
      {
        typeId: '2',
        name: 'potato',
        number: 16
      },
      {
        typeId: '3',
        name: 'potato',
        number: 10
      },
      {
        typeId: '4',
        name: 'tomato',
        number: 4
      },
      {
        typeId: '5',
        name: 'tomato',
        number: 21
      },
      {
        typeId: '6',
        name: 'vegetables',
        number: 3
      },
      {
        typeId: '7',
        name: 'vegetables',
        number: 13
      },
    ]
转换成以下数据 arr数据
    arr = [
      {
        typeId: ["6", "7"],
        name: 'vegetables',
        number: 16
      },
      {
        typeId: ["4", "5"],
        name: 'tomato',
        number: 25
      },
      {
        typeId: ["2", "3"],
        name: 'potato',
        number: 26
      }
    ]

把 数组 data中的子对象中 name属性相同的子对象的 number 合并,得到一个新的对象,从而返回一个新数组 arr, 有哪些比较好的方法?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

GroupBy 啊。会写 groupBy 之后你可以回答 js 话题下的大部分 json 遍历转化问题。

不知道将来 JS 的数组会不会加原生的 GroupBy 实现。

// 这个 groupBy 函数是通用的,无论需求怎么变,groupBy的实现不会变
function groupBy(arr, by) {
    return arr.reduce((groups, item) => {
        // 获取 item 的分组的 key
        const key = by(item);
        // 看看这个组是不是已经存在
        let group = groups.find(g => g.key === key);
        if(!group) {
            // 不存在就创建一个新组
            group = {key, items: []};
            groups.push(group);
        }
        // item 放入组中
        group.items.push(item);
        return groups;
    }, []);
}

// 就是 SQL 的翻版嘛
// select name, sum(number) from data group by name
groupBy(data, item => item.name)
    .map(g => ({
        name: g.key,
        typeId: g.items.map(item => item.typeId),
        number: g.items.reduce((sum, item) => sum + item.number, 0)
    }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...