xxxxxxxxxx
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
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 (const [key, value] of Object.entries(object1)) {
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
var p = {
"p1": "value1",
"p2": null,
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
xxxxxxxxxx
for (let user in obj) {
if (obj[user].online === true) {
//code
}
}
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
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(userObj) {
return ["Alan", "Jeff", "Sarah", "Ryan"].every(name =>
userObj.hasOwnProperty(name)
);
}