我有一个简单的问题。我有两个数组A和B,如果B具有相同的ID,我想保留A对象。 例如:
const A = [{id: "price", value: "1"}]
const B = [{id: "price", value: "0"}, {id: "number", value: "0"}]
预期结果:
[{id: "price", value: "1"}, {id: "number", value: "0"}}]
我该怎么做?
我试图将A和A映射到A内,但没有用。
答案 0 :(得分:4)
const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id)));
将A
中的所有对象与B
中不在的A
中的对象连接起来(这是通过仅过滤B
中不存在的对象来完成的) A
中具有相同ID的对象)。
示例:
const A = [{id: "price", value: "1"}];
const B = [{id: "price", value: "0"}, {id: "number", value: "0"}];
const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id)));
console.log(result);
答案 1 :(得分:0)
您将在合并数组上使用reduce
-还将value
转换为数字:
const A = [{id: "price", value: "1"}];
const B = [{id: "price", value: "0"}, {id: "number", value: "0"}];
const res = Object.values([...A, ...B].reduce((acc, { id, value }) => {
if (acc[id]) acc[id].value += parseInt(value);
else acc[id] = { id, value: parseInt(value) };
return acc;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 2 :(得分:0)
您可以尝试的另一种选择(我相信它将是O(n))是将数组转换为以id为键的对象,然后扩展(jquery.extend或纯js实现),然后将合并的对象转换回数组。
const A = [{id: "price", value: "1"}];
const B = [{id: "price", value: "0"}, {id: "number", value: "0"}];
//convert arrays to objects
var Bx = {};
B.forEach(i => Bx[i.id] = i);
var Ax = {};
A.forEach(i => Ax[i.id] = i);
//copy all matching id properties from A to B
A.forEach(i => Bx[i.id] = Ax[i.id]);
//convert the merged object to array
var C = [];
Object.getOwnPropertyNames(Bx).forEach(i => C.push(Bx[i]));
console.log(C);