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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.