Iterate over Properties of an JavaScript Object Example

 This JavaScript example shows three native ways to list/traverse object properties:
  1. for...in loops - This method traverses all enumerable properties of an object and its prototype chain
  2. Object.keys(o) - This method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o.
  3. Object.getOwnPropertyNames(o) - This method returns an array containing all own properties' names (enumerable or not) of an object o.

1. Using a for-in loop

The for...in statement iterates over all non-Symbol, enumerable properties of an object.
var txt = "";
var person = {fname:"Ramesh", lname:"Fadatare", age:29}; 
var x;
for (x in person) {
  txt += person[x] + " ";
}
Output:
"Ramesh Fadatare 29 "

2. Using Object.keys()

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
Output:
["a", "b", "c"]

3. Using Object.getOwnPropertyNames()

The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
const object1 = {
  a: 1,
  b: 2,
  c: 3
};

console.log(Object.getOwnPropertyNames(object1));
Output:
["a", "b", "c"]

Comments