Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON forEach get Key and Value

I have the following forEach loop over a JSON object called obj:

Object.keys(obj).forEach(function(){}); 

How can I make it console.log both key and value of each item inside the object?

Something like this:

Object.keys(obj).forEach(function(k, v){     console.log(k + ' - ' + v); }); 
like image 357
gespinha Avatar asked Sep 24 '15 00:09

gespinha


People also ask

How do I iterate keys in JSON?

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

How do you loop a JSON array?

To loop through a JSON array with JavaScript, we can use a for of loop. to loop through the json array with a for of loop. We assign the entry being looped through to obj . Then we get the value of the id property of the object in the loop and log it.

What is key in JSON object?

The two primary parts that make up JSON are keys and values. Together they make a key/value pair. Key: A key is always a string enclosed in quotation marks. Value: A value can be a string, number, boolean expression, array, or object.


1 Answers

Use index notation with the key.

Object.keys(obj).forEach(function(k){     console.log(k + ' - ' + obj[k]); }); 
like image 139
Josiah Keller Avatar answered Sep 22 '22 06:09

Josiah Keller