使用javascript更新层次结构对象的json
一个简单的问题,我想使用javascript更新json,而不需要迭代 示例:使用javascript更新层次结构对象的json,javascript,tree,iteration,Javascript,Tree,Iteration,一个简单的问题,我想使用javascript更新json,而不需要迭代 示例: { "parent":{ "id":"1", "status":"Bad", "children":[ { "id":"2", "status":"Good", "children":[ { "id":"3", "status":"Bad",
{ "parent":{
"id":"1",
"status":"Bad",
"children":[
{
"id":"2",
"status":"Good",
"children":[
{
"id":"3",
"status":"Bad",
"children":[
]
},
{
"id":"4",
"status":"Bad",
"children":[
]
}
]
},
{
"id":"4",
"status":"Bad",
"children":[
{
"id":"3",
"status":"Bad",
"children":[
]
},
{
"id":"4",
"status":"Bad",
"children":[
]
}
]
}
]
}}
在这个树结构中,id对于许多对象都是通用的。如果我想更新“3”的所有id的状态,目前我正在进行迭代以找到相应的id并更新状态。这是非常耗时的,有没有一种方法可以让我不用迭代就可以使用ID更新状态
我发现了一个名为“pinch”的js,但它没有用,它在内部执行相同的迭代。那么,有没有一种方法可以在不进行迭代的情况下更新状态呢
我也欢迎最好的遍历想法。您可以像这样存储对象:
objs = [
{"id":"1","status":"Bad",children:[]},
{"id":"2","status":"Good",children:[]},
{"id":"3","status":"Bad",children:[]},
{"id":"4","status":"Bad",children:[]}]
objs[0].children=[objs[1],objs[2]]
objs.map(function(t){t.status="Updated"})
function getChildren(children, map, current){
if( current != null && map.indexOf(current) != 0 )
return children || [];
if(current== null)
current = "";
if(!children){
//todo : here you can update "children" of the node you want, via ajax etc..
}
if(map == current)
return children;
var fchildren = [];
for(var i= 0; i < children.length; i++ ){
var n = children[i];
var node = {
"id" : n.id,
"name" : n.name,
"children": getChildren(n.children, map, current+(current?"-":"")+n.id )
};
fchildren.push(node);
}
return fchildren;
通过这种方式,JS通过链接处理参数,您可以对列表执行任何操作-更改也将显示在json obj中。您可以使用如下递归函数:
objs = [
{"id":"1","status":"Bad",children:[]},
{"id":"2","status":"Good",children:[]},
{"id":"3","status":"Bad",children:[]},
{"id":"4","status":"Bad",children:[]}]
objs[0].children=[objs[1],objs[2]]
objs.map(function(t){t.status="Updated"})
function getChildren(children, map, current){
if( current != null && map.indexOf(current) != 0 )
return children || [];
if(current== null)
current = "";
if(!children){
//todo : here you can update "children" of the node you want, via ajax etc..
}
if(map == current)
return children;
var fchildren = [];
for(var i= 0; i < children.length; i++ ){
var n = children[i];
var node = {
"id" : n.id,
"name" : n.name,
"children": getChildren(n.children, map, current+(current?"-":"")+n.id )
};
fchildren.push(node);
}
return fchildren;
如果没有某种形式的迭代,我不确定这是否可能。谢谢你的回复kevin Bowersox,有没有最好的遍历方法来更新json,正如我所期望的那样。user2864740,我知道你的想法,你想让我转换类似的映射,然后你想让我遍历,有没有具体的例子。请务必让我知道。听起来您没有利用数据上可能存在的限制。如果具有相同id的所有节点始终具有相同的状态,那么您真的应该重新构造json对象,这样您就有了一个将id映射到状态的对象,以及另一个表示已删除状态的节点树的对象。通过这种方式,您可以在固定时间内更新具有相同id的所有节点的状态,同时仍然能够使用间接寻址在固定时间内查找任何给定节点的状态。james,感谢您的回复。我展示了一个简单的示例,其中我只想更新单个参数。但在实际情况下,我想更新多个参数,如状态、颜色等,请您给我一个简单的例子,说明您要求我做什么。谢谢kirill,到目前为止,映射不是我的选择。。。我用深度搜索做了最好的遍历迭代。。。