Let's assume that you have the following object:
javascriptlet erik = { 'location': 'Barcelona', 'age': 31, 'height': '177 cm' }
Use a for ... in
to iterate through it:
javascriptfor(let key in erik){ console.log(key) } // location // age // height for(let key in erik){ console.log(erik[key]) } // Barcelona // 31 // 177 cm
Use a for ... of
loop to iterate through an array:
javascriptfor(let keys of Object.keys(erik)){ console.log(keys) } // location // age // height for(let values of Object.values(erik)){ console.log(values) } // Barcelona // 31 // 177 cm
Or you want to iterate through Object.entries()
:
javascriptfor(let entries of Object.entries(erik)){ console.log(entries) } // ['location', 'Barcelona'] // ['age', 31] // ['height', '177 cm'] for(let [key, value] of Object.entries(erik)){ console.log([key, value]) } // ['location', 'Barcelona'] // ['age', 31] // ['height', '177 cm']
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.