18

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 similar way to do the same in Javascript?

Structure I am trying to iterate over is:

{ 'meta.num_prod': 4,
  'meta.crtd_on': '2015-12-24T06:27:18.850Z',
  'meta.last_upd': '2015-12-24T06:46:12.888Z',
  's.103114': 
     { prod_id: '103114',
       product_type: 'normal',
       last_updated: '2015-12-24T06:28:44.281Z',
       qty: 3,
       created_on: '2015-12-24T06:27:18.850Z' },
  's.103553': 
     { prod_id: '103553',
       product_type: 'normal',
       last_updated: '2015-12-24T06:46:12.888Z',
       qty: 1,
       created_on: '2015-12-24T06:46:12.888Z' } }
m0meni
  • 16,006
  • 16
  • 82
  • 141
Ajay Pal Singh
  • 682
  • 1
  • 5
  • 16
  • 2
    Possible duplicate of [How do I enumerate the properties of a JavaScript object?](http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object) – Pang Dec 24 '15 at 07:09
  • @Pang answers there aren't that extensive. A little old too. – m0meni Dec 24 '15 at 07:11

2 Answers2

30

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 generator
function* 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] of objectEntries(jane)) {
    console.log(`${key}: ${value}`);
}
// Output:
// first: Jane
// last: Doe
m0meni
  • 16,006
  • 16
  • 82
  • 141
  • How is your answer "more extensive" then the one in the question Pang mentioned? There's also nothing new in it... And as Ajay is a beginner links to some **good** documentation should also be added. – Andreas Dec 24 '15 at 07:20
  • @Andreas There are 8 answers that all have `for...in` loops and nothing else. And I'll add documentation thanks for mentioning it. – m0meni Dec 24 '15 at 07:21
  • `for...in`, `Object.keys`, `$.each`, some custom methods (using `for...in`) and also one with a reference to `underscore.js`. – Andreas Dec 24 '15 at 07:24
  • @Andreas $.each isn't even mentioned on the whole page. Object.keys doesn't have an example, and most people don't even use underscore anymore; they use Lodash. It's an old thread, and I'm trying to help a guy see some more options without having to dig. Is there a problem with that? – m0meni Dec 24 '15 at 07:26
  • Now THAT's extensive! Thanks a tonne! Even though I was able to work around with @Pang's link! – Ajay Pal Singh Dec 24 '15 at 09:12
  • `Or you can use a for...in loop, but most people I know don't use them nowadays due to better alternatives.` what, if anything, is wrong with for loop? It appears to be simpler. – reducing activity Nov 23 '21 at 18:27
4

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

dmigo
  • 2,849
  • 4
  • 41
  • 62