jquery for each on a map with index, key and value

arrays, hashmap, javascript, jquery

Solution

`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 ] );
});

Problem

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

Original source