[英]How can I merge two arrays of objects in JavaScript
I have a simple question. 我有一个简单的问题。 I have two arrays A and B, I want to retain A objects if B has the same ID.
我有两个数组A和B,如果B具有相同的ID,我想保留A对象。 For example:
例如:
const A = [{id: "price", value: "1"}]
const B = [{id: "price", value: "0"}, {id: "number", value: "0"}]
Expected result: 预期结果:
[{id: "price", value: "1"}, {id: "number", value: "0"}}]
How can I do this? 我怎样才能做到这一点?
I tried to map A and foreach B inside A but it didn't work. 我试图将A和foreach B映射到A中,但它没有用。
const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id)));
Concatenate all the objects from A
with objects from B
that aren't in A
(which is done by filtering only objects from B
where there isn't an object in A
with the same id). 将来自
A
所有对象与来自B
的不在A
的对象连接起来(这通过仅过滤来自B
对象来完成,其中A
具有相同id的对象)。
Example: 例:
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);
You'd use reduce
on the merged array - also turn the value
into a number: 您在合并的数组上使用
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; }
Another option that you could try (I believe it would be O(n) ) is to convert arrays to objects with id as key then extend (jquery.extend or pure js implementation) then convert the merged object back to array. 您可以尝试的另一个选项(我相信它将是O(n))是将数组转换为id为key的对象然后扩展(jquery.extend或pure 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.