In JavaScript, you can loop over the keys and values of an object using several methods. Here are two common ways:
for...in
loop:let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(`Key: ${key}, Value: ${obj[key]}`);
}
Object.entries()
with forEach
:let obj = {a: 1, b: 2, c: 3};
Object.entries(obj).forEach(([key, value]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
Remember that the order of keys in JavaScript objects is not guaranteed if you're using an older version of JavaScript (prior to ES2015). In ES2015 and later, the order is guaranteed to be the same as the order in which the properties were added to the object.
Also, when using for...in
, it's recommended to use hasOwnProperty()
to ensure that the key is an object's own property, not an inherited one:
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(`Key: ${key}, Value: ${obj[key]}`);
}
}
This isn't necessary when using Object.entries()
, as it only returns an array of a given object's own enumerable string-keyed property key-value pairs.