OneCompiler

How to Loop over objects in Javascript

270

The better way to loop over Objects in Javascript is by converting them to arrays and use normal Array looping techniques.

You can convert an object to an array by using the following methods

1. Object.keys

This creates an array which contains the properties or keys of an object.

2. Object.values

This creates an array which contains the values of the properties or keys of an object.

3. Object.entries

This creates an array which contains the both keys and values of an object.

let info = {
  name: "foo",
  id: 123
}

const keys = Object.keys(info);
console.log(keys) ;  // [ 'name', 'id' ]

const values = Object.values(info);
console.log(values) ;  // [ 'foo', 123 ]

const arr = Object.entries(info);
console.log(arr) ;  // [ [ 'name', 'foo' ], [ 'id', 123 ] ]

The above example helps you to understand how you can convert objects to arrays. If you are using Object.entries then you need to destructure it while using like const [name,id] of arr.

Once the objects are converted to arrays, then you can use the normal array techniques as discussed here