iterate through object javascript
iterate over object javascript

Objects in JavaScript are data stored in string type that are stored as key-value pair. One of the important concept working with objects is iterations, Iteration in other words is traversing through the properties of object. In this JS article let’s checkout different ways to iterate through object in javascript.

referral Object

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    email: "john.doe@example.com",
    address: {
        street: "123 Main St",
        city: "Anytown",
        state: "CA",
        zipCode: "12345"
    },
    hobbies: ["reading", "traveling", "gardening"],
    isActive: true
};

JavaScript Methods to Iterate an Object

1. for…in Loop:

The for...in, javascript loop through object goes through all the enumerable elements/properties of an object, and also those that are inherited from its prototype chain.

for (let key in obj) {
    console.log(key, obj[key]);
}

result:

firstName: John
lastName: Doe
age: 30
email: john.doe@example.com
address: [object Object]
hobbies: reading,traveling,gardening
isActive: true

2. Object.keys() Method

The Object.keys() method returns all the keys items in an array.

const keys = Object.keys(person);
console.log(keys);

result

[
  'firstName',
  'lastName',
  'age',
  'email',
  'address',
  'hobbies',
  'isActive'
]

3. Object.values() Method

The Object.values() method returns all the values items in an array.

const values = Object.values(obj);
values.forEach(value => {
    console.log(value);
});

result

[
  'John',
  'Doe',
  30,
  'john.doe@example.com',
  {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA',
    zipCode: '12345'
  },
  [ 'reading', 'traveling', 'gardening' ],
  true
]

4. Object.entries() Method

The Object.entries() method returns a new array which contains all the value in key-value pairs in a form of array, example below.

const entries = Object.entries(person);
console.log(entries);

result:

[
  [ 'firstName', 'John' ],
  [ 'lastName', 'Doe' ],
  [ 'age', 30 ],
  [ 'email', 'john.doe@example.com' ],
  [
    'address',
    {
      street: '123 Main St',
      city: 'Anytown',
      state: 'CA',
      zipCode: '12345'
    }
  ],
  [ 'hobbies', [ 'reading', 'traveling', 'gardening' ] ],
  [ 'isActive', true ]
]

Note:

In JavaScript the order of iteration is not guaranteed in JS Object.

The loops methods like for...in can loop only enumerable properties but not non-enumerable properties in object. If you want to iterate object properties that are non-enumerable then you need to used methods like Object.getOwnPropertyName or Reflect.ownKeys().