按id搜索动态JSON

时间:2016-09-14 19:12:22

标签: javascript

我有一个具有以下结构的JSON:

{
 "root": {
    "containers": [
       {
         "id": UNIQUE_ID,
         ...
         "child": [
           {
             "id": UNIQUE_ID,
             ...
             "child": [...]
           }
         ]
       },

       {
         "id": UNIQUE_ID,
         ...
         "child": [...]
       }
    ]
  }
}

root.containers和root.containers.child具有相同的结构。问题是我可以有无限的嵌套,我事先不知道子节点的总数是多少,因为它们被动态地添加到这个JSON中。

我需要一个函数,只返回给定ID作为参数的特定对象。因此,必须深入研究JSON,直到找到具有该ID的孩子。我尝试过.filters,但我无法弄清楚如何更深入地搜索。可能是我之前从未在javascript中实现的一些搜索算法...

有人可以告诉我如何实现这一目标?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用这样的递归函数(https://jsfiddle.net/17qLjufc/):

//this is just a function to check for null or undefined
var notEmpty = function(something){
    if(typeof(something) !== 'undefined' && something !== null){
        return true;
    }
    return false;
}

//this is a recursive function that does the search in dept indefinetly (supposing that all the nodes from the containers node on just have child properties)
var findNodeById = function (node, id){
    if(notEmpty(node) && notEmpty(node.id) && node.id == id)
        return node;
    else{
        if(notEmpty(node) && notEmpty(node.child)){
            for (var i = 0 ; i < node.child.length; i++){
                var found = findNodeById(node.child[i], id);
                if(found != null)
                    return found;
                }
            }
        }
    return null;
}

//this is going through the containers children and call the search for each of them until the first is found.
var searchById = function(root, id){
    var found;
    if(notEmpty(root) && notEmpty(root.containers)){
        for(var i = 0; i < root.containers.length; i++){
            found = findNodeById(root.containers[i], id);
            if(found !== null){
                break;
            }
        }
    }
    return found;
}

答案 1 :(得分:1)

您需要的功能是:

function findById(data, id){
    var found;
    data.forEach(function(o){
        if(found){
            return;
        }
        found = o.id === id && o || o.child && findById(o.child, id);
    });

    return found;
}

它将以这种方式使用:

findById(data.root.containers, 1)

检查并运行以下代码段。它有一些测试,包括一个失败的案例。

var data = {
 "root": {
    "containers": [
       {
         "id": 1,
         "child": [
           {
             "id": 2,
             "child": [{
             	id: 3
             }, {
             	id: 4
             }]
           }
         ]
       },
       {
         "id": 5,
         "child": [{
           	id: 6
          }]
       },
       {
         "id": 7,
         "child": []
       }
    ]
  }
};

function findById(data, id){
	var found;
	data.forEach(function(o){
		if(found){
			return;
		}
		found = o.id === id && o || o.child && findById(o.child, id);
	});

	return found;
}

[1,2,3,4,5,6,7,8].forEach(function(v){
	console.log('==== Searching for:', v);
	 console.log(findById(data.root.containers, v));
});