JSON forEach gets key and value

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

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

How can I do this console.log both key and value for each element inside an object? Something like that:

 Object.keys(obj).forEach(function(k, v){ console.log(k + ' - ' + v); }); 

Is it possible?

+5
source share
4 answers

Use index notation with a key.

 Object.keys(obj).forEach(function(k){ console.log(k + ' - ' + obj[k]); }); 
+13
source

Assuming obj is a pre-built object (and not a JSON string), you can achieve this as follows:

 Object.keys(obj).forEach(function(key){ console.log(key + '=' + obj[key]); }); 
+4
source

Try something like this:

 var prop; for(prop in obj) { if(!obj.hasOwnProperty(prop)) continue; console.log(prop + " - "+ obj[prop]); } 
0
source

Another easy way to do this is to use the following syntax to iterate over an object while maintaining access to the key and value:

 for(var key in object){ console.log(key + ' - ' + object[key]) } 

so for yours:

 for(var key in obj){ console.log(key + ' - ' + obj[key]) } 
0
source

Source: https://habr.com/ru/post/1232153/


All Articles