以下是一个示例代码,演示如何按照值合并两个JavaScript对象数组:
const array1 = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Mike' },
{ id: 3, name: 'David' }
];
const array2 = [
{ id: 1, age: 25 },
{ id: 2, age: 30 },
{ id: 4, age: 35 }
];
function mergeArrays(array1, array2) {
const mergedArray = [];
// 遍历第一个数组
array1.forEach(obj1 => {
// 在第二个数组中查找匹配的对象
const matchedObj = array2.find(obj2 => obj2.id === obj1.id);
// 如果找到匹配的对象,则合并到一个新对象中
if (matchedObj) {
const mergedObj = {
id: obj1.id,
name: obj1.name,
age: matchedObj.age
};
mergedArray.push(mergedObj);
}
});
return mergedArray;
}
const mergedArray = mergeArrays(array1, array2);
console.log(mergedArray);
这段代码首先定义了两个要合并的对象数组array1
和array2
。然后定义了一个mergeArrays
函数,该函数接收两个数组作为参数。
函数内部首先创建了一个空数组mergedArray
,用于存储合并后的结果。
然后使用forEach
方法遍历了array1
数组,对于每一个对象,使用find
方法在array2
数组中查找匹配的对象。
如果找到了匹配的对象,则将两个对象的属性合并到一个新对象mergedObj
中,然后将新对象添加到mergedArray
数组中。
最后,返回合并后的数组。
在示例代码中,mergedArray
将会包含以下对象:
[
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Mike', age: 30 }
]
下一篇:按照值和键对键值对进行排序