How to group an array of objects by key

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

    For cases where key can be null and we want to group them as others

    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'},
                {'make':'kia','model':'optima','year':'2033'},
                {'make':null,'model':'zen','year':'2012'},
                {'make':null,'model':'blue','year':'2017'},
    
               ];
    
    
     result = cars.reduce(function (r, a) {
            key = a.make || 'others';
            r[key] = r[key] || [];
            r[key].push(a);
            return r;
        }, Object.create(null));
    

提交回复
热议问题