admin管理员组文章数量:1332377
I have just this array :
var sArray = {856:"users", 857:"avatars", 858:"emails"};
and I want to use forEach
in a way to get key and value from that:
key = 856
value = user
My $.each
code doesn't return the result I'm expecting, and I get instead:
856:user
I must be separate that with :
to get key and value from this array.
My code is:
$.each(template_array, function(key, value) {
console.log("key: " + "value: " + value);
});
How to access key and value without separate?
I have just this array :
var sArray = {856:"users", 857:"avatars", 858:"emails"};
and I want to use forEach
in a way to get key and value from that:
key = 856
value = user
My $.each
code doesn't return the result I'm expecting, and I get instead:
856:user
I must be separate that with :
to get key and value from this array.
My code is:
$.each(template_array, function(key, value) {
console.log("key: " + "value: " + value);
});
How to access key and value without separate?
Share Improve this question edited Sep 7, 2015 at 8:26 Gargaroz 3129 silver badges28 bronze badges asked Sep 7, 2015 at 7:45 user4790312user4790312 2-
You have
"value: " + value
, why not"key: " + key
– Shanimal Commented Sep 7, 2015 at 7:57 - I think issue is in your array, is this the exact code you are using? – Muhammad Bilal Commented Sep 7, 2015 at 7:59
4 Answers
Reset to default 4Just take Object.keys
for the keys and Array.prototype.forEach
for the values in plain Javascript.
var sArray = { 856: 'users', 857: 'avatars', 858: 'emails'};
Object.keys(sArray).forEach(function (key) {
document.write('key: ' + key + ', value: ' + sArray[key] + '<br>');
});
Just concatenate them using +
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
$.each(template_array, function(key, value) {
console.log('key:' + key + ', value:' + value);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
UPDATE : I think you have an array then use the following code
var template_array = ['856: users',
'857: avatars',
'858: emails'
];
template_array.forEach(function(v) {
v = v.split(':');
console.log('key:' + v[0] + ', value:' + v[1]);
});
try this one
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
var date = [];
$.each(template_array,function (key , val){
date.push({key:key, value:val})
});
console.log(date)
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
for (key in template_array) {
console.log('key:' + key + ', value:' + template_array[key]);
});
本文标签: jqueryJavaScript foreach Key Value arrayStack Overflow
版权声明:本文标题:jquery - JavaScript foreach Key Value array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742306174a2449962.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论