- In Case You may need to loop through Objects in JavaScript
for-in loop
When you loop through an object with the for…in the loop.
You need to check if the property belongs to the object.
You can do this with hasOwnProperty
.
for (var property in object) { if (object.hasOwnProperty(property)) { // Do things here } }
Ways to loop through objects javascript
Way to loop through objects is first to convert the object into an array and then loop.
Object.keys
Object.keys
creates an array that contains the properties of an object.
const trees = { "Eastern Redbud": "Cercis canadensis", "River Birch": "Betula nigra", "Sugar Maple": "Acer saccharum" } const keys = Object.keys(trees) console.log(keys); // [ 'Eastern Redbud', 'River Birch', 'Sugar Maple' ]
Object.values
Object.values
creates an array that contains the values of every property in an object.
const trees = { "Eastern Redbud": "Cercis canadensis", "River Birch": "Betula nigra", "Sugar Maple": "Acer saccharum" } const values = Object.values(trees) console.log(values) // [ 'Cercis canadensis', 'Betula nigra', 'Acer saccharum' ]
Object.entries
- Object. entries create an array of arrays.
- Each inner array has two items.
- The first item is the property.
- The second item is the value.
- You get both the key and property values.
const trees = { "Eastern Redbud": "Cercis canadensis", "River Birch": "Betula nigra", "Sugar Maple": "Acer saccharum" } const entries = Object.entries(trees) console.log(entries); // [ // [ 'Eastern Redbud', 'Cercis canadensis' ], // [ 'River Birch', 'Betula nigra' ], // [ 'Sugar Maple', 'Acer saccharum' ] //]
Looping through the array
- Now, You can loop through it as if it was a normal array.
const trees = { "Eastern Redbud": "Cercis canadensis", "River Birch": "Betula nigra", "Sugar Maple": "Acer saccharum" } const keys = Object.keys(trees) for (const key of keys) { console.log(key) } // Eastern Redbud // River Birch // Sugar Maple