Skip to content

JavaScript iterate object

JavaScript iterate object will access given object properties and values one by one in a loop. There are several ways to iterate over an object in JavaScript, including the for...in loop, Object.keys() method, Object.values() method, and Object.entries() method.

JavaScript iterate object example

Simple example code iterate over an object using various methods.

for...in loop: This loop is used to iterate over an object’s enumerable properties.

<!DOCTYPE html>
<html>
<body>
<script>
    let person = {
        name: 'John',
        age: 30,
        isStudent: false
    };

    for (let key in person) {
        console.log(`${key}: ${person[key]}`);
    }
</script>
</body>
</html>

Output:

JavaScript iterate object

Object.keys() method: This method returns an array of the object’s own enumerable properties.

Object.keys(person).forEach(key => {
  console.log(`${key}: ${person[key]}`);
});

Object.values() method: This method returns an array of the object’s own enumerable property values.

Object.values(person).forEach(val => {
  console.log(val);
});

Output:

John
30
false

Object.entries() method: This method returns an array of the object’s own enumerable property key-value pairs as arrays.

Object.entries(person).forEach(([key, val]) => {
  console.log(`${key}: ${val}`);
});

Comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “JavaScript iterate object”

  1. This method takes the Object we want to loop over as an argument and returns an array containing all key values. const population = { male: 4, …The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties … Javascript Maps keep keys in insertion order, meaning you can iterate over them without having to check the hasOwnProperty, which was always really a hack.
    https://spacebarcounter.us/

Leave a Reply

Your email address will not be published. Required fields are marked *