【根据id合并对象数组】
let arr1 = [
{ name: '小磊', age: '男', id: 1 },
{ name: '小李', age: '男', id: 2 },
{ name: '小张', age: '女', id: 2 },
]
let arr2 = [
{ figure: 98, id: 2 },
{ figure: 100, id: 1 },
]
let arr3 = arr1.map((item) => {
let matched = arr2.find((value) => value.id === item.id)
return matched ? {...item,...matched} : item;
})
console.log(arr3,'arr3');
//打印
//[
// { name: '小磊', age: '男', id: 1, figure: 100 },
// { name: '小李', age: '男', id: 2, figure: 98 },
// { name: '小张', age: '女', id: 2, figure: 98 }
//] arr3
注:1.此处是针对两个数组的合并;2.只能先遍历长度大的数组,再遍历长度小的数组;3.map方法不能改为forEach,因为forEach是没有返回值的
【递归查找树形数组中符合条件的项】
const treeData = [
{
id: 1,
name: '湖北',
children: [
{ id: 11, name: '武汉' },
{ id: 12, name: '宜昌' },
{ id: 12, name: '荆州' },
]
},
{
id: 2,
name: '广东',
children: [
{
id: 21,
name: '粤港澳大湾区',
children: [
{ id: 211, name: '深圳' },
{ id: 12, name: '广州' },
{ id: 12, name: '香港' },
]
}
]
}
];
/**
* 递归查找对象数组中符合条件的项
* @param {Array} arr - 要查找的对象数组(包含children属性)
* @param {Function} condition - 查找条件函数,返回布尔值
* @returns {Object|null} 找到的项或null
*/
function findItemInTree(arr, condition) {
// 遍历当前层级的每一项
for (const item of arr) {
// 检查当前项是否符合条件
if (condition(item)) {
return item;
}
// 如果当前项有children且是数组,递归查找子层级
if (item.children && Array.isArray(item.children) && item.children.length > 0) {
const found = findItemInTree(item.children, condition);
// 如果在子层级找到,直接返回
if (found) {
return found;
}
}
}
// 所有层级都遍历完仍未找到,返回null
return null;
}
console.log(findItemInTree(treeData,(item)=> item.id === 11))
//打印
//{ id: 11, name: '武汉' }
注:findItemInTree方法中第二个参数是函数