我试图返回JSON对象 struct 中的一个特定 node ,如下所示

{
    "id":"0",
    "children":[
        {
            "id":"1",
            "children":[...]
        },
        {
            "id":"2",
            "children":[...]
        }
    ]
}

所以这是一种树状的亲子关系.每node个都有一个唯一的ID. 我想找一个像这样的node

function findNode(id, currentNode) {

    if (id == currentNode.id) {
        return currentNode;
    } else {
        currentNode.children.forEach(function (currentChild) {            
            findNode(id, currentChild);
        });
    }
}  

例如,我以findNode("10", rootNode)为单位执行搜索.但是,即使搜索找到匹配项,函数也总是返回undefined.我有一种不好的预感,即递归函数在找到匹配项后不会停止,并继续运行最终返回undefined,因为在后面的递归执行中它没有到达返回点,但是我不确定如何修复这个问题.

请帮帮我!

推荐答案

递归搜索时,必须返回结果.不过,你不会返回findNode(id, currentChild)的结果.

function findNode(id, currentNode) {
    var i,
        currentChild,
        result;

    if (id == currentNode.id) {
        return currentNode;
    } else {

        // Use a for loop instead of forEach to avoid nested functions
        // Otherwise "return" will not work properly
        for (i = 0; i < currentNode.children.length; i += 1) {
            currentChild = currentNode.children[i];

            // Search in the current child
            result = findNode(id, currentChild);

            // Return the result if the node has been found
            if (result !== false) {
                return result;
            }
        }

        // The node has not been found and we have no more options
        return false;
    }
}

Json相关问答推荐

NIFI-我需要数组的信息,但只需要第一个信息

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

在Ruby的json中压缩单个字段

(Kotlin)com.google.gson.internal.LinkedTreeMap无法转换为com.example.phonetest2.model.HallData

使用 Powershell,如何将 Azure AD 组成员转换为 Json 对象(文件),然后可以更新?

为什么 Django Rest API 序列化器没有正确序列化多对多字段

使用 jq 从字符串列表开始创建对象

如何使用 jq 在连续的 json 记录流上调用操作

Golang gin接收json数据和图片

jq: Select 何时来自另一个数组的值与此 json 中的值匹配

如何在jolt中使用shift和modify-overwrite-beta

用于遮蔽卡的 Jolt 规格

如何迭代、动态加载我的表单输入元素,然后在 React 中的表单提交上检索输入值?

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

如何在 jQuery 中循环遍历 JSON 数组?

将 JSON 对象推送到 localStorage 中的数组

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

如何从 MySQL 中检索 JSON 数据?

如何遍历 JSON 中的条目?

从动态 json 数据更新力有向图上的链接