Why isn't is possible to use objects in for of loops? Or is this a browser bug? This code doesn't work in Chrome 42, saying undefined is not a function:
test = { first: "one"}
for(var item of test) {
console.log(item)
}
The for..of loop only supports iterable objects like arrays, not objects.
The outer forEach() loop is used to iterate through the objects array.
These include the string, list, tuple, dict, set, and frozenset types. But these are by no means the only types that you can iterate over.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With