50

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);
});

7 Answers 7

98

Use index notation with the key.

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

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
})
1
  • 2
    Object.entries is best answer if you have ES7+. thank you!
    – BoB3K
    Apr 3, 2020 at 17:47
7

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])
}
1
  • 3
    In this case, using hasOwnProperty is necessary, because the for...in construction includes properties inherited via the prototype chain. Sep 24, 2015 at 0:30
5

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]);
});
2
  • hasOwnProperty isn't necessary because Object.keys already only includes own properties. (MDN) Sep 24, 2015 at 0:18
  • Doenst Object.keys() ensures that only properties from the object itself are accessed? So no need for hasOwnProperty?
    – user4164128
    Sep 24, 2015 at 0:19
2

Try something like this:

var prop;
for(prop in obj) {
    if(!obj.hasOwnProperty(prop)) continue;

    console.log(prop + " - "+ obj[prop]);
}
1

Use forEach in combo with Object.entries().

const WALLPAPERS = [{
  WALLPAPER_KEY: 'wallpaper.image',
  WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
  WALLPAPER_KEY: 'lockscreen.image',
  WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];

WALLPAPERS.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(`${key} - ${value}`);
  }
});

0

I would do it this way. Assuming I have a JSON of movies ...

movies.forEach((obj) => {
  Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key} ${value}`);
  });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.