How to group an array of objects by key

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

    There is absolutely no reason to download a 3rd party library to achieve this simple problem, like the above solutions suggest.

    The one line version to group a list of objects by a certain key in es6:

    const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})
    

    The longer version that filters out the objects without the key:

    function groupByKey(array, key) {
       return array
         .reduce((hash, obj) => {
           if(obj[key] === undefined) return hash; 
           return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
         }, {})
    }
    
    
    var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
    
    console.log(groupByKey(cars, 'make'))

    NOTE: It appear the original question asks how to group cars by make, but omit the make in each group. So the short answer, without 3rd party libraries, would look like this:

    const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {})
    
    var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
    
    console.log(groupByKey(cars, 'make', {omitKey:true}))

提交回复
热议问题