Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have this array

var array = [ 

     { '1': '3PwGtv534oy9RTeWAAAB' }, 
     { '2': '_tKGtyOU6OtU6tdgPOGG' }, 
     { '3': '86JGHnjR3UJ88An09M32' } 
]


I want to retrieve both the key and the values of each object.

What I have tried:

for(var i in array){
   console.log(i);
   console.log(array[i]);
}


But it gives the object index in
console.log(i); 
and the object in
console.log(array[i]);


I also tried looping twice but it doesn't work either.
for(var i in array){
   for(var j in i){
     console.log(j);
     console.log(i[j]);
   }
}
Posted
Updated 18-Nov-17 2:53am

Here is a working example using jQuery: cp_json_get_key_value - JSFiddle[^]
 
Share this answer
 
Comments
SL-A-SH 18-Nov-17 3:45am    
Thank you so much. This is exactly what I wanted.
Karthik_Mahalingam 18-Nov-17 8:44am    
seems JSFiddle is down
getting Emergency maintenance, we are working on bringing JSFiddle back
Bryian Tan 18-Nov-17 8:48am    
is up again :)
Karthik_Mahalingam 18-Nov-17 8:49am    
yes :)
here is the javascript version
var array = [

    { '1': '3PwGtv534oy9RTeWAAAB' },
    { '2': '_tKGtyOU6OtU6tdgPOGG' },
    { '3': '86JGHnjR3UJ88An09M32' }
       ];
       for (var i = 0; i < array.length; i++) {
           var item = array[i];
           for (obj in item) {
               console.log(obj, item[obj]);
           }
       }
 
Share this answer
 
Comments
SL-A-SH 18-Nov-17 10:38am    
Yay thanks
Karthik_Mahalingam 18-Nov-17 10:49am    
Welcome
Laxmidhar tatwa technologies 27-Nov-17 7:30am    
good named variable array

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900