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 ?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Mick
  • 2,840
  • 10
  • 45
  • 61
  • possible duplicate of [I have a nested data structure / JSON, how can I access a specific value?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value) – Felix Kling Feb 18 '13 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. – Felix Kling Feb 18 '13 at 20:54
  • Maybe it's rather a duplicate of [Getting JavaScript object key list](http://stackoverflow.com/questions/3068534/getting-javascript-object-key-list). – Felix Kling Feb 18 '13 at 20:55
  • 1
    `children()` is for a jQuery set NOT for an array. Use the normal `Array` methods and accessors to get at array elements. – prodigitalson Feb 18 '13 at 20:56
  • @FelixKling - would'nt it be converted to an object anyway with those keys (asking cause I don't know, and I'm guessing you know these things ?). – adeneo Feb 18 '13 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`. – Felix Kling Feb 18 '13 at 20:56
  • @FelixKling - Yeah, but if you ran typeof, you'd get "object", right ? – adeneo Feb 18 '13 at 20:57
  • 1
    @adeneo: As I said, arrays *are* objects. Always. But that `typeof arr` returns `'object'` is rather a shortcoming of the language. – Felix Kling Feb 18 '13 at 20:58
  • @FelixKling - Okay, thanks (learns something new everyday!)! – adeneo Feb 18 '13 at 20:59

1 Answers1

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);
    });
}
Joel Grannas
  • 2,016
  • 2
  • 24
  • 46