根据id搜索动态JSON
Search dynamic JSON by id
我有一个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;
}
相关文章:
- 从 json 动态获取数据时出现类型错误
- 如何使用javascript Json动态添加到html表中
- 通过json动态绑定作用域到ng模型
- JSON动态Javascript解析”;未定义”;
- json动态菜单和路由
- 从 json 动态构建 dom 树
- 如何在 Angular JS 中使用 JSON 动态选择单选按钮
- 使用嵌套的JSON动态填充选择选项
- Mootools Request.JSON动态回调
- 通过json动态发送到服务器的表单数据不起作用
- 如何:在谷歌地图上从JSON动态更新标记
- 使用Backbone.Marionette从JSON动态生成站点导航
- 从JSON动态创建对象
- 当按钮按下或设置为true时,从JSON动态创建表单
- 用json动态加载树
- 如何从JSON动态生成HTML中嵌套的复选框列表?
- 当使用JSON动态填充一些字段时,我如何保持一些表单字段完整
- 从JSON动态定义ReactJS路由
- 从Google图表中的JSON动态填充数据
- 填充JSON动态数组