js iterate objects code example

Example 1: iterate object javascript

let obj = {
	key1: "value1",
	key2: "value2",
	key3: "value3",
	key4: "value4",
}
Object.entries(obj).forEach(([key, value]) => {
	console.log(key, value);
});

Example 2: javascript iterate object

const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // => [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

Object.entries(obj).forEach((key, value) => {
  console.log(key + ' ' + value);
});

Example 3: javascript iterate through object attributes

for (var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
        // do stuff
    }
}

Example 4: javascript iterate object

for (let key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}