我不知道是否有这样的方法:对象或地图来检查嵌套对象。
我的问题是我在其他对象中有对象。:/
我认为代码应该更深入: node.children[1].children[0].children[0].children[0].name;
但是我无法创建一个以这种方式递归的函数。
const rootNode = {
name: "node1",
children: [
{
name: "node2",
children: [
{
name: "node3",
tag: 251,
},
]
},
{
name: "node4",
children: [
{
name: 'node5',
children: [
{
name: "node7",
children: [
{
name: 'node8',
children: [
{
name: "node6"
},
],
},
],
},
],
},
]
},
]
}
// YOU CAN MODIFY THIS PART ONLY
/**
* Search a node by name inside a node
* @param node Any node to start the search in
* @param nodeName The name to search
* @returns undefined when no node is found or the founded node
*/
const searchInNodeByName = (node, nodeName) => {
}
// HERE ENDS WHAT YOU CAN MODIFY
const valueIsRecord = (value) => value !== null
&& typeof value === 'object'
&& !Array.isArray(value)
const node6 = searchInNodeByName(rootNode, 'node6')
if (
node6 === undefined
|| !valueIsRecord(node6)
|| node6.name !== 'node6'
) {
throw new Error('node6 should be found')
}
const node10 = searchInNodeByName(rootNode, 'node10')
if (node10 !== undefined) {
throw new Error('node10 should not be found')
}
const node3 = searchInNodeByName(rootNode, 'node3')
if (
node3 === undefined
|| !valueIsRecord(node3)
|| node3.name !== 'node3'
|| node3.tag !== 251
) {
throw new Error('node3 should be found')
}
console.log('IF YOU SEE THIS ON YOUR CONSOLE, YOU ARE DONE!')
const searchInNodeByName = (node, nodeName) => {
if (node['name'] == nodeName) {
return node;
}
else if (node['children'] != undefined) {
for (let i = 0; i < node['children'].length; i++) {
var checkChild = searchInNodeByName(node['children'][i], nodeName);
if (checkChild !== undefined) {
return checkChild;
}
}
}
return undefined;
}
此函数将检查给定的第一个节点,如果名称等于 nodeName 参数,则返回该节点。否则,如果该节点中有子节点,它将遍历所有子节点,并执行递归函数以到达节点参数内的所有节点,优先处理节点对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句