Reputation: 8732
If I have data which looks something like this:
x = {"key1":"val1", "key2":"val2", "key3", "val3"};
Is there any standard way to do a for each over them with a function that returns the key, value and index?
The way I would do it is define an array of keys and use the index to access it, but is there a simpler way?
something like:
$.each(x, function(i, k, v) {
//... do something here
}
Upvotes: 3
Views: 11714
Reputation: 235982
Object.keys()
link along with Array.prototype.forEach
link:
Synopsis
Object.keys( object ).forEach(function( element, index, array ) {
});
Object.keys()
returns all own keys as Array and .forEach()
loops over an array like shown above. Since we get an Array from Object.keys()
, we can of course also apply Array.prototype.sort()
on it, and access the keys in any order we like. For instance
Object.keys( object ).sort(function( a, b ) {
return a.localeCompare( b );
}).forEach(function( element, index, array ) {
console.log( object[ element ] );
});
Upvotes: 6
Reputation: 4675
you can create your own "index" if you will
var i =0;
$.each(...... {
/* code */
i++;
});
Upvotes: 1