How to group an array of objects by key

后端 未结 24 3459
后悔当初
后悔当初 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:34

    Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.

    Array.prototype.groupBy = function(k) {
      return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
    };
    
    const projs = [
      {
        project: "A",
        timeTake: 2,
        desc: "this is a description"
      },
      {
        project: "B",
        timeTake: 4,
        desc: "this is a description"
      },
      {
        project: "A",
        timeTake: 12,
        desc: "this is a description"
      },
      {
        project: "B",
        timeTake: 45,
        desc: "this is a description"
      }
    ];
    
    console.log(projs.groupBy("project"));
    

提交回复
热议问题