JavaScript iterate sobre o objeto
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Bald Eagle
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
const obj = { a: 1, b: 2 };
Object.keys(obj).forEach(key => {
console.log("key: ", key);
console.log("Value: ", obj[key]);
} );
for (var property in object) {
if (object.hasOwnProperty(property)) {
// Do things here
}
}
// Looping through arrays created from Object.keys
const keys = Object.keys(fruits)
for (const key of keys) {
console.log(key)
}
// Results:
// apple
// orange
// pear
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
// for-in
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
// for-of with Object.keys()
for (var key of Object.keys(p)) {
console.log(key + " -> " + p[key])
}
// Object.entries()
for (let [key, value] of Object.entries(p)) {
console.log(`${key}: ${value}`);
}
const object = { a: 1, b: 2, c: 3 };
// method 1
Object.entries(object).forEach(([key, value]) => {
console.log(key, value)
});
//method 2
for (const key in object) {
console.log(key, object[key])
}
// same output
// a 1
// b 2
// c 3