使用Javascript在分组数组中添加新记录

时间:2018-12-10 13:47:01

标签: javascript arrays

我想在我的分组数组中添加新记录。例如

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' }];

var 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);

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我想以下将会做到:

const result = {"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"}]};

const addCar = (result, car) =>
    Object.keys(result).some((k) => k === car.make)//see if car exists
        ? { ...result, [car.make]: result[car.make].concat(car) }//it does
        : { ...result, [car.make]: [car] };//it does not

console.log(addCar(result, { make: 'kia', model: 'hello world' }).kia);