How to group an array of objects by key

后端 未结 24 2904
后悔当初
后悔当初 2020-11-21 05:13

Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav

24条回答
  •  旧巷少年郎
    2020-11-21 05:44

    function groupBy(data, property) {
      return data.reduce((acc, obj) => {
        const key = obj[property];
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
      }, {});
    }
    groupBy(people, 'age');
    

提交回复
热议问题