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

}

Comments

  1. You could use for of to iterate over the object values as well:

    for (petValue of pets) {
    console.log(petValue);
    }

    ReplyDelete
  2. Yup, iterating using

    for (item of items) {
    //
    }

    Returns an item "of the items",

    Rather than an index of an item "of the items"

    ReplyDelete

Post a Comment

Popular posts from this blog

What is 'this.' keyword in JavaScript

How to create promises in JavaScript

How to make a static http server in nodejs using express

How to make a Snake Game using JavaScript and html5

How to get user's ip address in JavaScript