JSON forEach get Key and Value
Another easy way to do this is by using the following syntax to iterate through the object, keeping 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])
}
Assuming that obj
is a pre-constructed object (and not a JSON string), you can achieve this with the following:
Object.keys(obj).forEach(function(key){
console.log(key + '=' + obj[key]);
});
Loop through object with arrow functions
ES6
Object.keys(myObj).forEach(key => {
console.log(key + ' - ' + myObj[key]) // key - value
})
ES7
Object.entries(myObj).forEach(([key, value]) => {
console.log(key + ' - ' + value) // key - value
})
Use index notation with the key.
Object.keys(obj).forEach(function(k){
console.log(k + ' - ' + obj[k]);
});