如何动态遍历JSON数据并进行更改..?

时间:2013-01-16 11:58:15

标签: javascript arrays json parsing object

我有一张类似JSON数据的地图

var map =  {        
    level1 : {          
            x : {name:'level1 x' , },
            y : {name:'level1 y'}
    },
    level2 : {          
            x : {name:'level2 x'},
            y : {name:'level2 y'}
    }

}

我需要遍历这些数据,我将遍历路径作为字符串

"level1 x name" , "level2 y name";

如何解析该字符串路径中的JSON数据.. ??

我尝试的是,

var path = "level1 x name".split(" ");
var pointer = map; // assuming it will take reference of map and change will cause to map also
 for (var i = 0, len = path.length; i < len; i++) {
   if(pointer){
      pointer = pointer[path[i]];
   }else{
     pointer = map[path[i]];
   } 
 }
 pointer = "level1 xx";

console.log(map);

但是地图数据没有改变..如何通过引用循环并更改值..?

2 个答案:

答案 0 :(得分:1)

这就是你获得价值的方式:

var name = [map].concat("level1 x name".split(" ")).reduce(function(prev, curr) {
    return prev[curr];
});

console.log(name);

// -> 'level1 x'

JavaScript按值传递参数,而不是按引用传递。

为方便起见,我更改了您的代码,以便您完成所要求的内容:

var path = "level1 x name".split(" ");
var pointer = map; // assuming it will take reference of map and change will cause to map also
 for (var i = 0, len = path.length-1; i < len; i++) {
   if(pointer){
      pointer = pointer[path[i]];
   }else{
     pointer = map[path[i]];
   } 
 }
 pointer[path[path.length-1]] = "level1 xx";

console.log(map);

答案 1 :(得分:-2)

试试这个..根据需要更改路径变量。它工作正常。我刚用萤火虫验证了它。

var map =  {        
    level1 : {          
            x : {name:'level1 x' , },
            y : {name:'level1 y'}
    },
    level2 : {          
            x : {name:'level2 x'},
            y : {name:'level2 y'}
    }
};
var path = "level1 x name";
var pathInfor = path.split(' ');
var pathLength = pathInfor.length;
//alert(map[pathInfor[0]][pathInfor[1]][pathInfor[2]].name);

for(level in map)
{
    if(level == pathInfor[0]){
       var selLevel = map[level];
        for(xy in selLevel)
        {
           if(xy == pathInfor[1])
           {
                  var selVariable = map[level][xy];
                    for(innerVal in selVariable){
                               if(innerVal == pathInfor[2]){
                               alert(map[level][xy][innerVal]);
                               }
                    }
           }
        }
    }
}

在此方法中,您无需检查值。如果要从JSON打印所有值,请删除条件。