Iterating over a dictionary in Javascript
There are multiple ways to this one standard way is using Object.keys:
You can do
- Object.keys
- Array.Prototype.forEach
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
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