JavaScript从json迭代键和值?(复制)

时间:2022-08-23 08:10:10

This question already has an answer here:

这个问题已经有了答案:

I am trying to iterate the following json:

我尝试迭代以下json:

{
"VERSION" : "2006-10-27.a",
"JOBNAME" : "EXEC_",
"JOBHOST" : "Test",
"LSFQUEUE" : "45",
"LSFLIMIT" : "2006-10-27",
"NEWUSER" : "3",
"NEWGROUP" : "2",
"NEWMODUS" : "640"
}

Here key is dynamic. I want both key = ? and value = ?

这里关键是动态的。我要两把钥匙= ?和价值= ?

2 个解决方案

#1


17  

Use Object.keys() to get keys array and use forEach() to iterate over them.

使用Object.keys()获取密钥数组,并使用forEach()来遍历它们。

var data = {
  "VERSION": "2006-10-27.a",
  "JOBNAME": "EXEC_",
  "JOBHOST": "Test",
  "LSFQUEUE": "45",
  "LSFLIMIT": "2006-10-27",
  "NEWUSER": "3",
  "NEWGROUP": "2",
  "NEWMODUS": "640"
};

Object.keys(data).forEach(function(key) {
  console.log('Key : ' + key + ', Value : ' + data[key])
})

#2


14  

You can use Object.keys for that.

您可以使用对象。键。

var keys = Object.keys(yourObject);
for(var i=0;i<keys.length;i++){
    var key = keys[i];
    console.log(key, yourObject[key]);
}

#1


17  

Use Object.keys() to get keys array and use forEach() to iterate over them.

使用Object.keys()获取密钥数组,并使用forEach()来遍历它们。

var data = {
  "VERSION": "2006-10-27.a",
  "JOBNAME": "EXEC_",
  "JOBHOST": "Test",
  "LSFQUEUE": "45",
  "LSFLIMIT": "2006-10-27",
  "NEWUSER": "3",
  "NEWGROUP": "2",
  "NEWMODUS": "640"
};

Object.keys(data).forEach(function(key) {
  console.log('Key : ' + key + ', Value : ' + data[key])
})

#2


14  

You can use Object.keys for that.

您可以使用对象。键。

var keys = Object.keys(yourObject);
for(var i=0;i<keys.length;i++){
    var key = keys[i];
    console.log(key, yourObject[key]);
}