如何使用Javascript物件key對陣列array進行group分群組

7 月 1, 2019 | Javascript, | 0 comments

通過物件key對array進行分組,然後根據分組創建一個新的物件陣列?例如以下,有一個car陣列物件,要對make這個key作為分組關鍵:

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

outupt

{
  audi: [
    {
      make: audi,
      model: r8,
      year: 2012
    },
    {
      make: audi,
      model: rs5,
      year: 2013
    }
  ],
  ford: [
    {
      make: ford,
      model: mustang,
      year: 2012
    },
    {
      make: ford,
      model: fusion,
      year: 2015
    }
  ],
  kia: [
    {
      make: kia,
      model: optima,
      year: 2012
    }
  ]
}