extracting key value pairs of an array in javascript with jquery Jan
06
1
1

At times I feel spoiled using Python, especially when I try to do what seems to be a trivial operation to discover there's not already a construct to do it in whatever language I'm in at the time. One of these instances is when I try to loop over and extract key value pairs out of an array in Javascript. Being in the Python mode I'm usually hoping to find something like the following:

# python
for key, value in array:
    ....

The best I could come up with is to use the each() function from JQuery to loop over each element.

var example = {};

example['apple'] = 1;
example['orange'] = 2;

$.each(example, function(key, value) {
    console.log(key);
    console.log(value);
});

Or, for a non-jquery solution:

for(var key in example) {
    console.log(key);
    console.log(example[key]);
}
Bookmark and Share
blog comments powered by Disqus