Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript iterate key & value from json? [duplicate]

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

like image 282
Prashant Vhasure Avatar asked Jun 07 '16 07:06

Prashant Vhasure


People also ask

How do I iterate over a key in JavaScript?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

How do you iterate keys?

The Object. keys() method was introduced in ES6. It takes the object that you want to iterate over as an argument and returns an array containing all properties names (or keys). You can then use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.


2 Answers

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]) })
like image 172
Pranav C Balan Avatar answered Oct 12 '22 13:10

Pranav C Balan


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]); }
like image 20
Jamiec Avatar answered Oct 12 '22 12:10

Jamiec