JavaScript iterate key & value from json?

JavascriptArraysJson

Javascript Problem Overview


I am trying to iterate the following 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 = ?

Javascript Solutions


Solution 1 - Javascript

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

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])
})

Solution 2 - Javascript

You can use Object.keys for that.

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]);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrashant VhasureView Question on Stackoverflow
Solution 1 - JavascriptPranav C BalanView Answer on Stackoverflow
Solution 2 - JavascriptJamiecView Answer on Stackoverflow