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
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);
});
Using Array Destruction you can iterate it as follows using forEach
const obj = { a: 5, b: 7, c: 9 };
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
I just did the following to easily console out my stuff.
for (let key in obj) {
if(obj.hasOwnProperty(key){
console.log(`${key}: ${obj[key]}`);
}
}
What about using
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
for ([key, value] of entries({a: "1", b: "2"})) {
console.log(key + " " + value);
}
How about using Object.keys to get an array of keys? And then forEach on the Array?
obj = { a: 1, b:2}
Object.keys(obj).forEach( key => console.log(`${key} => ${obj[key]}`))
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