Ways of iterating Object properties in JavaScript
For Objects the ways of iterating their properties are not that plentiful as with Arrays.
take for instance we have an object of dogs and cat characteristics
const pets = {
{name: "Jenny", eyes: "brown"},
{name: "max", eyes: "blue"}
}
To iterate through the characteristics using for loop
for (pet in pets) {
console.log(`${pets[pet].name} has eye color ${pets[pet].eyes}`}
}
Alternatively you can use objects.keys and object.entries
for (element in Object.entries(elements))
}
You could use for of to iterate over the object values as well:
ReplyDeletefor (petValue of pets) {
console.log(petValue);
}
Yup, iterating using
ReplyDeletefor (item of items) {
//
}
Returns an item "of the items",
Rather than an index of an item "of the items"