Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  109] [ 6]  / answers: 1 / hits: 34219  / 9 Years ago, thu, december 24, 2015, 12:00:00

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' } }

More From » object

 Answers
5

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

[#63956] Tuesday, December 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;