迭代重度嵌套的javascript对象以查找数据

时间:2015-07-29 15:24:30

标签: javascript

我有以下JavaScript对象模式。

{
    "_id": 2,
    "children": [
    {
        "_id": 3,
        "children": [
        {
            "_id": 5,
            "children": [
            {
                "_id": 9,
                "children": [],
                "id_category": 9,
                "parent_id": 5
            },
            {
                "_id": 10,
                "children": [],
                "id_category": 10,
                "parent_id": 5
            }],
            "id_category": 5,
            "parent_id": 3
        },
        {
            "_id": 6,
            "children": [],
            "id_category": 6,
            "parent_id": 3
        }],
        "id_category": 3,
        "parent_id": 2
    },
    {
        "_id": 4,
        "children": [
        {
            "_id": 7,
            "children": [],
            "id_category": 7,
            "parent_id": 4
        },
        {
            "_id": 8,
            "children": [],
            "id_category": 8,
            "parent_id": 4
        }],
        "id_category": 4,
        "parent_id": 2
    }],
    "id_category": 2,
    "parent_id": 1
}

现在我想获得传递_id值的全部数据。 例如,如果我传递5,它将返回5

的整个对象
{
    "_id": 5,
    "children": [
    {
        "_id": 9,
        "children": [],
        "id_category": 9,
        "parent_id": 5
    },
    {
        "_id": 10,
        "children": [],
        "id_category": 10,
        "parent_id": 5
    }],
    "id_category": 5,
    "parent_id": 3
}

问题是嵌套级别是无限的。

请建议。

1 个答案:

答案 0 :(得分:0)

使用递归函数。

像这样(未经测试,但应该没问题)

function search(value, tree) {
    if (tree._id === value)
        return value;

    var numChildren = tree.children.length;
    for (var i = 0; i < numChildren; ++i) {
        var result = search(value, tree.children[i]);
        if (result)
            return result;
    }

    return null;
}

var tree = {...your big json hash...};
var found = search(5, tree);

console.log(found);