1 回答
TA贡献1842条经验 获得超21个赞
希望这就是您正在寻找的:
const input = {
"children": [{
"name": "test",
"title": "test 1",
"id": "t1",
"children": [
]
},
{
"name": "test",
"title": "test 2",
"id": "t2",
"children": [{
"name": "Dummy 1",
"title": "dummy",
"id": "dummy1",
"children": [
]
},
{
"name": "Dummy 2",
"title": "dummy2",
"id": "dummy2",
"children": [{
"name": "Dummy 2.1",
"title": "dummy2.1",
"id": "dummy2.1",
"children": [
]
}]
}
]
},
{
"name": "home 1",
"title": "home 1",
"id": "h1",
"children": [{
"name": "room 1",
"title": "room 1",
"id": "room1",
"children": [{
"name": "Dummy 4.1",
"title": "dummy4.1",
"id": "dummy4.1",
"children": [
]
},
{
"name": "test",
"title": "test 4",
"id": "test4",
"children": [
]
}
]
}]
},
{
"name": "home 2",
"title": "home 2",
"id": "h2",
"children": [{
"name": "room 2",
"title": "room 2",
"id": "room2",
"children": [{
"name": "Dummy 5.1",
"title": "dummy5.1",
"id": "dummy5.1",
"children": [
]
},
{
"name": "test",
"title": "test 6",
"id": "test6",
"children": [
]
},
{
"name": "test",
"title": "test 7",
"id": "test7",
"children": [
]
}
]
}]
},
{
"name": "home 3",
"title": "home 3",
"id": "h3",
"children": [{
"name": "room 2",
"title": "room 2",
"id": "room2",
"children": [{
"name": "Dummy 5.1",
"title": "dummy5.1",
"id": "dummy5.1",
"children": [
]
},
{
"name": "test",
"title": "test 6",
"id": "test6",
"children": [
]
},
{
"name": "computer",
"title": "computer1",
"id": "computer1",
"children": [{
"name": "Dummy 7.1",
"title": "dummy7.1",
"id": "dummy7.1",
"children": [
]
},
{
"name": "test",
"title": "test 10",
"id": "test10",
"children": [
]
}
]
}
]
}]
}
]
}
function findChild(obj, condition) {
if (Object.entries(condition).every(([k, v]) => obj[k] === v)) {
return obj;
}
const children = []
if (obj.children.length > 0) {
for (const child of obj.children) {
const found = findChild(child, condition);
// If found, then add this node to the ancestors of the result
if (found)
children.push(found);
}
obj.children = children;
return obj;
}
return null;
}
var search = {
name: 'test'
};
console.dir(findChild(input, search), {
depth: null
});
添加回答
举报