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]);
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742306174a4418985.html
评论列表(0条)