如何根据另一个对象数组更新对象数组

时间:2017-10-17 18:25:36

标签: javascript arrays javascript-objects

我有两个数组:

initial=[{code:"1",size: 0},{code:"2",size: 0},{code:"3",size: 0},{code:"4",size: 0}];
update=[{code:"1",size: 100},{code:"2",size: 100},{code:"2",size: 120}];

我需要得到这样的新数组:

我想按代码字段进行分组,并在分组后进行尺寸总和。

new=[{code:"1",size: 100},{code:"2",size: 220},{code:"3",size: 0},{code:"4",size: 0}];

5 个答案:

答案 0 :(得分:2)

您可以使用具有相同代码的对象的哈希表。



var initial = [{ code: "1", size: 0 }, { code: "2", size: 0 }, { code: "3", size: 0 }, { code: "4", size: 0 }],
    update = [{ code: "1", size: 100 }, { code: "2", size: 100 }, { code: "2", size: 120 }],
    hash = Object.create(null),
    result = initial.map(function (o) {
        return hash[o.code] = { code: o.code, size: 0 };
    });

update.forEach(function (o) {
    hash[o.code].size += o.size;
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

检查一下 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

答案 2 :(得分:0)

您可以使用.map()的{​​{1}},.filter().reduce()方法



Array.prototype




答案 3 :(得分:0)

以下是函数式编程样式中使用ES6 Map的版本:

function addObjects(acc, add) {
    return Array.from(
        add.reduce((mp, {code, size}) => mp.set(code, mp.get(code) + size),
                new Map(acc.map(({code, size}) => [code, size]))),
        ([code, size]) => ({code, size})
    );
} 

const initial = [{ code: "1", size: 0 }, { code: "2", size: 0 }, { code: "3", size: 0 }, { code: "4", size: 0 }],
      update = [{ code: "1", size: 100 }, { code: "2", size: 100 }, { code: "2", size: 120 }];

const res = addObjects(initial, update);

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 4 :(得分:0)

您可以使用array#concat加入数组,然后使用array#reduce汇总对象内的大小,然后从该对象中获取值。



const initial=[{code:"1",size: 0},{code:"2",size: 0},{code:"3",size: 0},{code:"4",size: 0}],
      update=[{code:"1",size: 100},{code:"2",size: 100},{code:"2",size: 120}];

let result = initial
              .concat(update)
              .reduce((res, {code, size}) => {
                res[code] = {code, size : (res[code]|| {size:0}).size + size};
                return res;
              },Object.create(null));

let output = Object.values(result);
console.log(output);

.as-console-wrapper { max-height: 100% !important; top: 0; }