Thursday, November 10, 2022

Loop object best approches

combine Object.keys() and Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };

Option One: 

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

Option Two: 


for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

Option Three: 

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


Option Four: 

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

No comments:

Post a Comment