admin管理员组

文章数量:1291602

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
}

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
}
Share Improve this question asked Mar 10, 2013 at 21:08 Omar WagihOmar Wagih 8,7447 gold badges64 silver badges75 bronze badges 2
  • 1 Just plain old for() and manual counter? – zerkms Commented Mar 10, 2013 at 21:10
  • 3 Objects' keys are unordered in nature. Most browsers will iterate them in the order the properties were added, but they are not warranted to. – Fabrício Matté Commented Mar 10, 2013 at 21:12
Add a ment  | 

2 Answers 2

Reset to default 6

Object.keys()link along with Array.prototype.forEachlink:

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

you can create your own "index" if you will

var i =0;
$.each(...... {
    /* code */
    i++;
});

本文标签: javascriptjquery for each on a map with indexkey and valueStack Overflow