简体   繁体   中英

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:

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM