How to group an array of objects by key

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

    Here is another solution to it. As requested.

    I want to make a new array of car objects that's grouped by make:

    function groupBy() {
      const key = 'make';
      return cars.reduce((acc, x) => ({
        ...acc,
        [x[key]]: (!acc[x[key]]) ? [{
          model: x.model,
          year: x.year
        }] : [...acc[x[key]], {
          model: x.model,
          year: x.year
        }]
      }), {})
    }
    

    Output:

    console.log('Grouped by make key:',groupBy())
    

提交回复
热议问题