How to group an array of objects by key

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

    Create a method which can be re-used

    Array.prototype.groupBy = function(prop) {
          return this.reduce(function(groups, item) {
            const val = item[prop]
            groups[val] = groups[val] || []
            groups[val].push(item)
            return groups
          }, {})
        };
    

    Then below you can group by any criteria

    const groupByMake = cars.groupBy('make');
            console.log(groupByMake);
    

    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'
        },
    ];
      //re-usable method
    Array.prototype.groupBy = function(prop) {
    	  return this.reduce(function(groups, item) {
    		const val = item[prop]
    		groups[val] = groups[val] || []
    		groups[val].push(item)
    		return groups
    	  }, {})
    	};
      
     // initiate your groupBy. Notice the recordset Cars and the field Make....
      const groupByMake = cars.groupBy('make');
    		console.log(groupByMake);
        
        //At this point we have objects. You can use Object.keys to return an array

提交回复
热议问题