Javascript使用对象遍历json对象

时间:2018-01-19 13:56:06

标签: javascript json

我的json字符串有一个特例,我不知道如何获得我需要的所有信息。这是重新格式化的字符串:

        {  
           "0":{  
              "-1":"",
              "0":"VOR_CVR",
              "1":"VOR_CVR2",
              "2":"VOR_CVR3",
              "3":"VOR_CVR4",
              "4":"VOR_CVR5"
           },
           "1":{  
              "-1":"",
              "0":"VOR_RMV",
              "1":"VOR_FND",
              "2":"VOR_FND2",
              "3":"FAGGIO3_MGUARD1",
              "4":"VOR_FND3",
              "5":"VOR_FND4"
           }
}

我需要获取外部0和1以及内部数字(不带字符串)。 这是我的代码:

var mods = JSON.parse(string); //contains the json string
for (var key in mods) {
    for (var key2 in mods[key]) {
            console.log(key);
            console.log(key2);
    }
}



var string = `{  
               "0":{  
                  "-1":"",
                  "0":"VOR_CVR",
                  "1":"VOR_CVR2",
                  "2":"VOR_CVR3",
                  "3":"VOR_CVR4",
                  "4":"VOR_CVR5"
               },
               "1":{  
                  "-1":"",
                  "0":"VOR_RMV",
                  "1":"VOR_FND",
                  "2":"VOR_FND2",
                  "3":"FAGGIO3_MGUARD1",
                  "4":"VOR_FND3",
                  "5":"VOR_FND4"
               }
    }`
var mods = JSON.parse(string); //contains the json string
for (var key in mods) {
  for (var key2 in mods[key]) {
    console.log(key);
    console.log(key2);
  }
}




1 个答案:

答案 0 :(得分:1)

Object.Keys循环中的mods[key]上使用for

var string = JSON.stringify({
	"0": {
		"-1": "",
		"0": "VOR_CVR",
		"1": "VOR_CVR2",
		"2": "VOR_CVR3",
		"3": "VOR_CVR4",
		"4": "VOR_CVR5"
	},
	"1": {
		"-1": "",
		"0": "VOR_RMV",
		"1": "VOR_FND",
		"2": "VOR_FND2",
		"3": "FAGGIO3_MGUARD1",
		"4": "VOR_FND3",
		"5": "VOR_FND4"
	}
});

var mods = JSON.parse(string); //contains the json string
for (var key in mods) {
  console.log(key);
  // console.log(mods[key]);
  var keys = Object.keys(mods[key]);
  console.log(keys);

}