Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Objects in For Of Loops

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)
}
like image 245
Daniel Herr Avatar asked Apr 27 '15 00:04

Daniel Herr


People also ask

Can we use a object in for..of loop?

The for..of loop only supports iterable objects like arrays, not objects.

Which loop is used for array of objects?

The outer forEach() loop is used to iterate through the objects array.

What are the types of objects allowed for iteration in for loops for item in obj do something with object?

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.


2 Answers

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];
}
like image 110
Overv Avatar answered Oct 22 '22 20:10

Overv


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.

like image 56
mpen Avatar answered Oct 22 '22 19:10

mpen