xxxxxxxxxx
// Iterate Through the Keys of an Object
const usersObj = {
Alan: {
online: false,
},
Jeff: {
online: true,
},
Sarah: {
online: false,
},
};
function countOnline(usersObj) {
let count = 0;
for (let user in usersObj) {
if (usersObj[user].online === true) count++;
}
return count;
}
console.log(countOnline(usersObj));
xxxxxxxxxx
'use strict';
// ECMAScript 2017
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
xxxxxxxxxx
// `for...of` loop
for (const [key, value] of Object.entries(animals)) {
console.log(`${key}: ${value}`);
}
// `forEach()` method
Object.entries(animals).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
xxxxxxxxxx
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
xxxxxxxxxx
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42"
xxxxxxxxxx
const fruits = { apple: 28, orange: 17 }
for(key in fruits){
console.log(key)
}
xxxxxxxxxx
var p = {
"p1": "value1",
"p2": null,
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
xxxxxxxxxx
const population = {
male: 4,
female: 93,
others: 10
};
let genders = Object.keys(population);
console.log(genders); // ["male","female","others"]
xxxxxxxxxx
const person = {
name: "John",
age: 30,
favoriteColors: ["Red", "Green"]
};
const keys = Object.keys(person);
// Output: ["name", "age", "favoriteColors"]
// 1. Using a for() loop
for (let i = 0; i < keys.length; i++) {
console.log(keys[i]);
}
// Output: "name", "age", "favoriteColors"