Skip to content
Advertisement

How to iterate (keys, values) in JavaScript? [duplicate]

I have a dictionary that has the format of

JavaScript

How can I iterate through this dictionary by doing something like

JavaScript

Advertisement

Answer

tl;dr

  1. In ECMAScript 2017, just call Object.entries(yourObj).
  2. In ECMAScript 2015, it is possible with Maps.
  3. In ECMAScript 5, it is not possible.

ECMAScript 2017

ECMAScript 2017 introduced a new Object.entries function. You can use this to iterate the object as you wanted.

JavaScript

Output

JavaScript

ECMAScript 2015

In ECMAScript 2015, there is not Object.entries but you can use Map objects instead and iterate over them with Map.prototype.entries. Quoting the example from that page,

JavaScript

Or iterate with for..of, like this

JavaScript

Output

JavaScript

Or

JavaScript

Output

JavaScript

ECMAScript 5:

No, it’s not possible with objects.

You should either iterate with for..in, or Object.keys, like this

JavaScript

Note: The if condition above is necessary only if you want to iterate over the properties which are the dictionary object’s very own. Because for..in will iterate through all the inherited enumerable properties.

Or

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement