Jump to content

$.each() Get Key Value?


chachew

Recommended Posts

So i am looping through a JSON string and i want to get the value of the key itself. I want to get this so i can use it to populate some navigation type menus. I can access elements of the object by:

 obj.A1.description 

and it will give me the value of the description object but i want to get the value of the key itself. Instead of knowing that the key is A1 i want to pull the value of each key with the $.each loop.

 

Current JSON string:

{"pack1":{"A1":{"description":"some text goes here","image":"image1 here"}},"pack2":{"A2":{"description":"more text here","image":"image2 here"}}}

Link to comment
https://forums.phpfreaks.com/topic/270800-each-get-key-value/
Share on other sites

You could do something like this to loop through each, then loop through each of the arrays in the array.

 

Javascript / jQuery

$(document).ready(function()
{
   var arr = {
       "pack1": {
           "A1": {
               "description": "some text goes here",
               "image": "image1 here"
           }
       },
       "pack2": {
           "A2": {
               "description": "more text here",
               "image": "image2 here"
           }
       }
   };

   $.each(arr, function(index, pack)
   {
       $.each(pack, function(i, a)
       {
           alert(a['image'] + " : " + a['description']);
       });
   });
});

Link to comment
https://forums.phpfreaks.com/topic/270800-each-get-key-value/#findComment-1393043
Share on other sites

Oh, I should also mention that the index of the function in the $.each loop is the key of the array as you were looking for it. What I did was loop through the packs, then loop through the inner array (A1 for example) and called the description and image key myself since they're the same.

Link to comment
https://forums.phpfreaks.com/topic/270800-each-get-key-value/#findComment-1393044
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.