function findObjectByCode(arr, code) {
for (let obj of arr) {
if (obj.code === code) {
return obj; // 如果找到了与指定 code 匹配的对象,则返回该对象
}
if (obj.child && obj.child.length > 0) {
const result = findObjectByCode(obj.child, code);
if (result) {
return result; // 如果在 child 数组中找到匹配的对象,则返回该对象
}
}
}
return null; // 如果没有找到匹配的对象,则返回 null
}
const arr = [
{
name: 1,
code: 'one',
child: [
{
name: '1-1',
code: 'one-one'
}
]
},
{
name: 2,
code: 'two',
child: [
{
name: '2-1',
code: 'two-one'
},
{
name: '2-2',
code: 'two-two',
child: [
{
name: '2-2-1',
code: 'two-two-one'
}
]
}
]
}
];
const result = findObjectByCode(arr, 'two-two-one');
console.log(result); // 输出 { name: '2-2-1', code: 'two-two-one' }
对象数组深层嵌套时 find 某一项
最新推荐文章于 2024-08-09 10:42:44 发布
该文章展示了一个JavaScript函数,用于在嵌套数组结构中通过指定的code值递归查找匹配的对象。函数遍历每个对象并检查其code属性,如果找到匹配项则返回对象;同时检查child属性以处理嵌套结构。示例展示了如何找到具有特定code的子对象。
摘要由CSDN通过智能技术生成