根据id搜索动态JSON

Search dynamic JSON by id

本文关键字:JSON 动态 搜索 id 根据      更新时间:2023-09-26

我有一个JSON与以下结构:

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

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

我需要一个函数,它只返回给定ID作为参数的特定对象。因此它必须深入JSON,直到找到具有该ID的子节点。我试过一些过滤器,但我不知道如何搜索更深。可能是一些我以前从未在javascript中实现过的搜索算法…

谁能给我一个主意,我怎么才能做到这一点?谢谢!

您需要的功能是:

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));
});

您可以使用这样的递归函数(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;
}