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 index notation with the key.
Object.keys(obj).forEach(function(k){
console.log(k + ' - ' + obj[k]);
});
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
})
ES8
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]);
});
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])
}
Try something like this:
var prop;
for(prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
console.log(prop + " - "+ obj[prop]);
}
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}`);
});
});
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}`); } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.