Using Objects in For Of Loops
If you are storing data in a key-value store, please use Map
which is explicitly designed for this purpose.
If you have to use an object though, ES2017 (ES8) allows you to use Object.values
:
const foo = { a: 'foo', z: 'bar', m: 'baz' };
for (let value of Object.values(foo)) {
console.log(value);
}
If that isn't supported yet, use a polyfill: Alternative version for Object.values()
And finally if you're supporting an older environment that don't support this syntax, you'll have to resort to using forEach
and Object.keys
:
var obj = { a: 'foo', z: 'bar', m: 'baz' };
Object.keys(obj).forEach(function (prop) {
var value = obj[prop];
console.log(value);
});
The for..of loop only supports iterable objects like arrays, not objects.
To iterate over the values of an object, use:
for (var key in test) {
var item = test[key];
}
You can use this syntax:
const myObject = {
first: "one",
second: "two",
};
for (const [key, value] of Object.entries(myObject)) {
console.log(key, value); // first one, second two
}
However, Object.entries
has poor support right now does not work in IE or iOS Safari. You'll probably might need a polyfill. See https://caniuse.com/mdn-javascript_builtins_object_entries for the latest scoop.
See also Object.keys
to iterate just the keys, or Object.values
for just the values.