来自 json 的 JavaScript 迭代键和值?

我尝试重复下面的 json:

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

这里的 key 是动态的。我需要两个 key = ? 和 value = ?

133631 次浏览

使用 < a href = “ https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global _ Objects/Object/keys”rel = “ norefrer”> Object.keys() 获取键数组并使用 < a href = “ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global _ Objects/Array/foreach”rel = “ noReferrer”> 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])
})

你可以使用 Object.keys

const yourObject = {
"VERSION": "2006-10-27.a",
"JOBNAME": "EXEC_",
"JOBHOST": "Test",
"LSFQUEUE": "45",
"LSFLIMIT": "2006-10-27",
"NEWUSER": "3",
"NEWGROUP": "2",
"NEWMODUS": "640"
}
const keys = Object.keys(yourObject);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
console.log(key, yourObject[key]);
}