0

I have a data structure like this:

var r =  
{ 
 "abc": ["a1","a2","a3"] ,
 "xyz": ["x1","x2","x3"] 
}

I am accessing these elements like this

jQuery.each(r,function(index,ele){ 
      alert(ele);    // values like a1,a2,a3 in ele -loop
});

I am getting values a1, a2, a3 in elements in ele variable.

I want to access values abc and xyz.

how to access value abc in loop?

fiddle: [fiddle]: http://jsfiddle.net/ce58qutw/

2
  • 2
    That isn't JSON. It is just an object. Commented Aug 11, 2014 at 13:49
  • Using each over an object the index and ele arguments are key and value, respectively. Now you alert the value under ele argument, but you want the key, which is under index. Commented Aug 11, 2014 at 13:50

5 Answers 5

1

Try,

jQuery.each(r,function(index,ele){ 
   alert(index);   
});

Keep in mind that the first parameter to the call back function is key and the second one is the value.

And the proper code would be,

jQuery.each(r,function(key,val){ 
   alert(key);   
});

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Try using a for..in loop:

for (var key in r) {
    alert(key);
};

Example fiddle

Comments

0

..Demo..try this,

$.each(r,function(index,ele){ 
    if(index==="abc"){
    for(i=0;i<ele.length;i++){   alert(ele[i]);    }
   }
 });

Comments

0

You can also do it using vanilla JS very easily:

Object.keys(r).forEach(function (key) {
  alert(key);
});

Comments

0

In your case, result will be an object and it looks like a dictionary to me having key value pairs.

You could do something like this

$.each(value, function (key, value) {
alert(key) // that's your key value    
this['prop_name'];  // iterate over your value object
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.