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); });
Use Object. keys() to get keys array and use forEach() to iterate over them.
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.
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.
Use index notation with the key.
Object.keys(obj).forEach(function(k){ console.log(k + ' - ' + obj[k]); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With