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

I have a dictionary that has the format of

    dictionary = {0: {object}, 1:{object}, 2:{object}}

How can I iterate through this dictionary by doing something like

    for((key,value) in dictionary){
      //Do stuff where key would be 0 and value would be the object
    }

This question is related to javascript dictionary object iterator ecmascript-7

The answer is


You can use JavaScript forEach Loop:

myMap.forEach((value, key) => {
    console.log('value: ', value);
    console.log('key: ', key);
});

You can use below script.

var obj={1:"a",2:"b",c:"3"};
for (var x=Object.keys(obj),i=0;i<x.length,key=x[i],value=obj[key];i++){
    console.log(key,value);
}

outputs
1 a
2 b
c 3


As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:

for (var key in dictionary) {
    if (!dictionary.hasOwnProperty(key)) {
        continue;
    }
    console.log(key, dictionary[key]);
}

Edit: info about Object.hasOwnProperty here


You can do something like this :

dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);

for(var i = 0; i < keys.length;i++){
   //keys[i] for key
   //dictionary[keys[i]] for the value
}

Try this:

dict = {0:{1:'a'}, 1:{2:'b'}, 2:{3:'c'}}
for (var key in dict){
  console.log( key, dict[key] );
}

0 Object { 1="a"}
1 Object { 2="b"}
2 Object { 3="c"}

WELCOME TO 2020 *Drools in ES6*

Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

Object.entries(myObject).forEach(([k,v]) => {
    console.log("The key: ",k)
    console.log("The value: ",v)
})
_x000D_
_x000D_
_x000D_

Edit:

As mentioned by Lazerbeak, map allows you to cycle an object and use the key and value to make an array.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

const myArray = Object.entries(myObject).map(([k, v]) => {
    return `The key '${k}' has a value of '${v}'`;
});

console.log(myArray);
_x000D_
_x000D_
_x000D_


Try this:

var value;
for (var key in dictionary) {
    value = dictionary[key];
    // your code here...
}

The Object.entries() method has been specified in ES2017 (and is supported in all modern browsers):

for (const [ key, value ] of Object.entries(dictionary)) {
    // do something with `key` and `value`
}

Explanation:

  • Object.entries() takes an object like { a: 1, b: 2, c: 3 } and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].

  • With for ... of we can loop over the entries of the so created array.

  • Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key and value to its first and second item.


I think the fast and easy way is

Object.entries(event).forEach(k => {
    console.log("properties ... ", k[0], k[1]); });

just check the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries


using swagger-ui.js

you can do this -

_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
    console.log(n, key);
 });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to iterator

Iterating over Typescript Map Update row values where certain condition is met in pandas How to iterate (keys, values) in JavaScript? How to convert an iterator to a stream? How to iterate through a list of objects in C++ How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? How to read one single line of csv data in Python? 'numpy.float64' object is not iterable Python list iterator behavior and next(iterator) python JSON only get keys in first level

Examples related to ecmascript-7

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined How to iterate (keys, values) in JavaScript? How can I clone a JavaScript object except for one key? Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11