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
2 Answers
Reset to default 6Object.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 ] );
});
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
版权声明:本文标题:javascript - jquery for each on a map with index, key and value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741537258a2384099.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论