loop through an object in javascript code example

Example 1: javascript loop through object

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

Example 2: js loop through object

const obj = { a: 1, b: 2 };

Object.keys(obj).forEach(key => {
	console.log("key: ", key);
  	console.log("Value: ", obj[key]);
} );

Example 3: javascript loop through object

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

Example 4: how to loop trough an object java script

// Looping through arrays created from Object.keys
const keys = Object.keys(fruits)
for (const key of keys) {
  console.log(key)
}

// Results:
// apple
// orange
// pear

Example 5: js loop through object

for (var property in object) {
  if (object.hasOwnProperty(property)) {
    // Do things here
  }
}

Example 6: javascript for in loop

const p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (let [key, value] of Object.entries(p)) {
  console.log(`${key}: ${value}`);
}