[英]JavaScript foreach Key Value array
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:我想以某种方式使用
forEach
从中获取键和值:
key = 856
value = user
My $.each
code doesn't return the result I'm expecting, and I get instead:我的
$.each
代码没有返回我期望的结果,而是得到:
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?如何在不分开的情况下访问键和值?
Just take Object.keys
for the keys and Array.prototype.forEach
for the values in plain Javascript.只需将
Object.keys
用作键,将Array.prototype.forEach
用作纯 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.com/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]); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.