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:
te
Object literals don't have built-in iterators, which are required to work with for...of
loops. However, if you don't want to go thru the trouble of adding your own [Symbol.iterator]
to your object, you can simply use the Object.keys()
method. This method returns an Array
object, which already has a built-in iterator, so you can use it with a for...of
loop like this:
const myObject = {
country: "Canada",
province: "Quebec",
city: "Montreal"
}
for (let i of Object.keys(myObject)) {
console.log("Key:", i, "| Value:", myObject[i]);
}
//Key: country | Value: Canada
//Key: province | Value: Quebec
//Key: city | Value: Montreal