Iterate over Properties of an JavaScript Object Example

 This JavaScript example shows three native ways to list/traverse object properties:
  1. 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 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] + " ";
"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

["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

["a", "b", "c"]