简体   繁体   中英

how to group object array to multidimensional array in javascript

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' }],
    result = cars.reduce(function (r, a) {
        r[a.make] = r[a.make] || [];
        r[a.make].push(a);
        return r;
    }, Object.create(null));

console.log(result);

out put is like comes like this

{
"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"}]}

But Expected Output is a multidimensional array

[  
[{"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"}]

]  

Take only the values from the object with Object.values .

 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' }], result = Object.values(cars.reduce(function (r, a) { r[a.make] = r[a.make] || []; r[a.make].push(a); return r; }, Object.create(null))); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Simply use this modified version with Object.values()

 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' }], result = cars.reduce(function (r, a) { r[a.make] = r[a.make] || []; r[a.make].push(a); return r; }, Object.create(null)); const newResult = Object.values(result); console.log(newResult);

Also you can use Array.prototype.map()

 const 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' }], const result = [...Object.values(cars).map(obj => obj)]; console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM