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' } }
Try this: var value; for (var key in dictionary) { value = dictionary[key]; // your code here... }
The Object. keys() method was introduced in ES6. It takes the object that you want to iterate over as an argument and returns an array containing all properties names (or keys). You can then use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.
Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With