Skip to content Skip to sidebar Skip to footer

Iterating Over A Dictionary In Javascript

I am fairly new to Javascript- and trying to iterate over a dictionary in Javascript. I can easily do so in python: for key, value in dict.items(): //do something Is there a s

Solution 1:

There are multiple ways to this one standard way is using Object.keys:

You can do

Object.keys(obj).forEach(function(key) {
   console.log(key + " " + obj[key]);
});

If you are using jQuery you can use $.each() method like this:

$.each({ name: "John", lang: "JS" }, function( k, v ) {
  console.log( "Key: " + k + ", Value: " + v );
});

Or you can use a for...in loop, but most people I know don't use them nowadays due to better alternatives.

for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}

If you ever end up wanting to complicate things you can use es6 generators like this to get syntax more akin to python:

// The asterisk after `function` means that// `objectEntries` is a generatorfunction* objectEntries(obj) {
    let propKeys = Reflect.ownKeys(obj);

    for (let propKey of propKeys) {
        // `yield` returns a value and then pauses// the generator. Later, execution continues// where it was previously paused.yield [propKey, obj[propKey]];
    }
}

let jane = { first: 'Jane', last: 'Doe' };
for (let [key,value] ofobjectEntries(jane)) {
    console.log(`${key}: ${value}`);
}
// Output:// first: Jane// last: Doe

Solution 2:

EcmaScript 2017 has Object.entries that comes in handy in situations like this one. MDN

const obj = { 
    'meta.num_prod': 4,
    'meta.crtd_on': '2015-12-24T06:27:18.850Z',
    'meta.last_upd': '2015-12-24T06:46:12.888Z',
}

Object.entries(obj).forEach(function([key, value]) {
   console.log(`${key}${value}`);
});

Output:

meta.num_prod 4 meta.crtd_on 2015-12-24T06:27:18.850Z meta.last_upd 2015-12-24T06:46:12.888Z

Post a Comment for "Iterating Over A Dictionary In Javascript"