![](/img/trans.png)
[英]JavaScript compare two arrays and push items to the first array that have the same property value in the second array
[英]Comparing two arrays, have one property from first to second where id of element is same
我正在学习 javascript 并希望通过比较它们来处理两个 arrays 并进行一些属性合并:
我的 array1 和 array2 为:
array1 = [
{ id: 10, name: 'abc', otherData: 'other' },
{ id: 20, name: 'def', otherData: 'other' },
{ id: 30, name: 'ghi', otherData: 'other' },
];
array2 = [
{ id: 10, nameV2: 'xyz', otherData: 'other' },
{ id: 20, nameV2: 'pqr', otherData: 'other' },
{ id: 30, nameV2: 'tvs', otherData: 'other' },
];
我期待这个结果,我将比较 arrays,迭代元素,如果 id 相同,则在array1's
元素中具有来自array2
的nameV2
键
预期 output:
array1 = [
{ id: 10, name: 'abc', otherData: 'other', nameV2: 'xyz' },
{ id: 20, name: 'def', otherData: 'other', nameV2: 'pqr' },
{ id: 30, name: 'ghi', otherData: 'other', nameV2: 'tvs' },
];
我应该如何做到这一点?
这是一种方法,我们使用 array2 创建一个查找映射 ( idNameV2Map
),然后使用它来获取所需的 output
const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }]; const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }]; const idNameV2Map = array2.reduce((acc, curr) => { acc[curr.id] = curr.nameV2; return acc; }, {}); const output = array1.map((item) => { if (idNameV2Map[item.id]) { return {...item, nameV2: idNameV2Map[item.id] }; } return item; }); console.log(output);
使用Array.find()
的另一种方法
如果存在,则有条件地将nameV2
属性添加到 object 中。
const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }]; const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }]; const output = array1.map((item) => { let objFound = array2.find(obj=>obj.id===item.id); return {...item, ...(objFound && {nameV2: objFound.nameV2}) }; }); console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.