1

我有一个类似 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);

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

4

2 回答 2

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);
于 2013-01-16T12:02:00.207 回答
-2

试试这个.. 根据需要更改路径变量。它工作正常。我刚刚在firebug中验证了它。

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 格式的所有值,请删除条件。

于 2013-01-16T12:12:17.830 回答