使用LoDash从含children数组的对象数组中查找属性匹配值的对象
嵌套集合中查找属性匹配特定值的对象
核心思路:递归遍历
因为你的集合是递归嵌套结构(每个对象可能包含children数组,数组里的对象又可能有自己的children),所以最直接的方法是用递归遍历——逐个检查每个对象的目标属性,同时递归处理它的子节点,直到找到匹配项或遍历完所有节点。
单匹配查找(找到第一个匹配对象就返回)
如果只需要找到第一个符合条件的对象,可以用这个函数:
function findNestedObject(items, propName, targetValue) { // 遍历当前层级的所有对象 for (const item of items) { // 检查当前对象的目标属性是否匹配 if (item[propName] === targetValue) { return item; } // 如果当前对象有children数组,递归查找子节点 if (item.children && Array.isArray(item.children)) { const foundItem = findNestedObject(item.children, propName, targetValue); if (foundItem) { return foundItem; } } } // 遍历完所有节点都没找到,返回null return null; }
使用示例(结合你的数据)
假设你的集合存在menuData变量中,现在要找value等于41的对象:
const menuData = [{ "value": 39, "label": "Bangalore", "path": "fa fa-tachometer", "parentmenu": null, "layout": null, "children": [{ "value": 40, "label": "Building1", "path": "fa fa-tachometer", "parentmenu": 39, "layout": null, "children": [{ "value": 41, "label": "Floor1", "path": "fa fa-tachometer", "parentmenu": 40, "layout": null }] }] }]; // 查找value为41的对象 const matchedItem = findNestedObject(menuData, 'value', 41); console.log(matchedItem); // 输出:{ value: 41, label: "Floor1", path: "fa fa-tachometer", parentmenu: 40, layout: null }
多匹配查找(收集所有符合条件的对象)
如果集合中可能存在多个匹配的对象,想要一次性收集全部结果,可以修改函数返回数组:
function findAllNestedObjects(items, propName, targetValue, results = []) { for (const item of items) { if (item[propName] === targetValue) { results.push(item); } if (item.children && Array.isArray(item.children)) { findAllNestedObjects(item.children, propName, targetValue, results); } } return results; }
使用示例
// 假设你的数据中有多个匹配项,调用后会返回所有符合条件的对象数组 const allMatchedItems = findAllNestedObjects(menuData, 'value', 39); console.log(allMatchedItems);
注意事项
- 如果你的属性值是复杂类型(比如对象、数组),需要把
===改成深度比较逻辑(比如用JSON.stringify临时转换后对比,或者自定义深度比较函数) - 函数里加了
Array.isArray(item.children)的判断,避免因children不是数组导致报错
内容的提问来源于stack exchange,提问作者Vikram Maiya
相关产品推荐
相关产品推荐

