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

FlappingBird Postmortem (JS13K)

JavaScript introduction to variables

FlappingBird JS13K Games

How to target all elements of a given class name in JavaScript

Zedplug will be decommissioned on November 30th