1

Assume I have an array in my script and it's made up like this:

   var detail= {};
   detail['i100']=new Array()

   detail['i100']['ID 4564']= 'John'  
   detail['i100']['ID 4899']= 'Paul' 
   detail['i100']['ID 9877']= 'Andy'
   detail['i100']['ID 1233']= 'Evan'

   detail['i25'] = new Array()  

   detail['i25']['ID 89866']= 'Paul s'  
   detail['i25']['ID 87866']= 'Paul'  

I then use this script to get the values of the first part of the array:

   $.each(detail, function(vehicle) {
    console.log( vehicle ) 
   });

This gives me two results as expected (i100 and i25), What I want to do however is, by using the reference vehicle, get all the names and values of the second dimension – i.e. by using i25 I want to return ID 89866 and ID 87866. I have tried children(), but it is just not working. Does anyone have any advice, please ?

9
  • possible duplicate of I have a nested data structure / JSON, how can I access a specific value? Commented Feb 18, 2013 at 20:54
  • 3
    Btw, you really should not use arrays with anything else than numerical keys. detail['i100']=new Array() should be detail['i100'] = {}, i.e. it should be an object. Commented Feb 18, 2013 at 20:54
  • 1
    children() is for a jQuery set NOT for an array. Use the normal Array methods and accessors to get at array elements. Commented Feb 18, 2013 at 20:56
  • 1
    @adeneo: Well, arrays are objects, but they have special methods that only work on properties with numerical property names. The code is totally valid, but e.g. detail['i25'].length would return 0. Commented Feb 18, 2013 at 20:56
  • 1
    @adeneo: As I said, arrays are objects. Always. But that typeof arr returns 'object' is rather a shortcoming of the language. Commented Feb 18, 2013 at 20:58

1 Answer 1

2

You need to run another each on the 2nd dimension.

$.each(detail, function(index,value){
    $.each(value, function(i,v) {
        console.log(v);
    });
});

or if you want to specifically call one item, pass in the value name:

function getByName(name){
    $.each(detail[name], function(i,v){
        console.log(v);
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried that but I get this error Uncaught TypeError: Cannot use 'in' operator to search for '3' in i100
try it now with my edits... i forgot each callback function uses (index,value)
No prob! Glad you got it. The best way to show your appreciation is to upvote and accept my answer :)

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.