JSON对象中的JavaScript递归搜索 [英] JavaScript recursive search in JSON object

查看:191
本文介绍了JSON对象中的JavaScript递归搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试返回JSON对象结构中的特定节点,该结构看起来像这样

I am trying to return a specific node in a JSON object structure which looks like this

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

所以它是一个类似树的子父关系。每个节点都有一个唯一的ID。
我正在尝试找到这样的特定节点

So it's a tree-like child-parent relation. Every node has a unique ID. I'm trying to find a specific node like this

function findNode(id, currentNode) {

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

我执行搜索,例如 findNode(10,rootNode)。但即使搜索找到匹配项,该函数也始终返回 undefined 。我有一种不好的感觉,递归函数在找到匹配后不会停止并继续运行finally返回 undefined 因为在后面的递归执行中它没有达到返回点,但我不知道如何解决这个问题。

I execute the search for example by findNode("10", rootNode). But even though the search finds a match the function always returns undefined. I have a bad feeling that the recursive function doesn't stop after finding the match and continues running an finally returns undefined because in the latter recursive executions it doesn't reach a return point, but I'm not sure how to fix this.

请帮忙!

推荐答案

递归搜索时,必须通过返回结果传回结果。但是,你没有返回 findNode(id,currentChild)的结果。

When searching recursively, you have to pass the result back by returning it. You're not returning the result of findNode(id, currentChild), though.

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对象中的JavaScript递归搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆