76

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 = ?

Prashant Vhasure
  • 916
  • 2
  • 7
  • 18

2 Answers2

151

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])
})
Jamiec
  • 133,658
  • 13
  • 134
  • 193
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 2
    Great answer !!! Is there any way to do it with map where each element has key and value (Something built in) ? I usually create helper function which does this but I'm looking for something to use ES6,7 – Pini Cheyni Dec 03 '19 at 08:02
45

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

Or Object.entries

const yourObject = {
  "VERSION": "2006-10-27.a",
  "JOBNAME": "EXEC_",
  "JOBHOST": "Test",
  "LSFQUEUE": "45",
  "LSFLIMIT": "2006-10-27",
  "NEWUSER": "3",
  "NEWGROUP": "2",
  "NEWMODUS": "640"
}
const entries = Object.entries(yourObject);
for (let [key,value] of entries) {
  console.log(key, value);
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193