Crystal Miller Crystal Miller - 3 months ago 20
jQuery Question

Select Nested object in $.map

How do I select a nested object's key in something like the following code?

dominant = {
"owner1":{
"sub1":{
"super_sub1":"Amy",
"super_sub2":"Luara",
"super_sub3":"Daria",
"super_sub4":"Maria"
},
"sub2":{
"extra_sub1":"Puppy",
"extra_sub2":"Dog",
"extra_sub3":"Wolf",
"extra_sub4":"Pet"
}
},
"owner2":{
"sub1":{"super_sub1":"Issaballa"},
"sub2":{"extra_sub1":"Puppy"}
},
"owner3":{
"sub1":{
"super_sub1":"Mary",
"super_sub2":"Amy",
"super_sub3":"Laura",
"super_sub4":"Daria"
},
"sub2":{
"extra_sub1":"Wolf",
"extra_sub2":"Dog"
}
},
"owner4":{
"sub1":{
"super_sub1":{"name":"Maria", "cords":[2,1,36,1,29,15,9,15]},
"super_sub2":{"name":"Daria", "cords":[37,5,37,33,31,25,31,14]},
"super_sub3":{"name":"Luara", "cords":[9,23,29,23,36,37,2,37]},
"super_sub4":{"name":"Amy", "cords":[1,5,7,14,7,25,1,33]},
"super_sub5":{"name":"Issaballa", "cords":[9,16,29,16,29,22,9,22]}
},
"sub2":{
"extra_sub1":{"name":"Puppy", "cords":[2,1,36,1,27,8,11,8]},
"extra_sub2":{"name":"Dog", "cords":[37,1,37,37,29,30,29,8]},
"extra_sub3":{"name":"Wolf", "cords":[11,30,27,30,36,37,2,37]},
"extra_sub4":{"name":"Pet", "cords":[1,1,9,8,9,30,1,37]},
"extra_sub5":{"name":"BarkBark", "cords":[10,10,28,10,28,28,10,28]}
}
},
};
$.map(dominant, function(dom, domi){
console.log("DOM:");console.log(dom);//equal to owners {}
console.log("DOMI:");console.log(domi);//equal to owners
return (
"<div class='tt_sect "+tvi+"'></div>"
);
}).join("")


I would like to select the key in the owners object (sub1 & sub2) inside the $.map. How would I do this? I know it can't be too difficult.

Answer

As far I understand your question, you need to access sub1 and sub2 , so here is the way, if you only want to do with map is

$.map(dominant, function(dom, domi){
    console.log("DOM:");console.log(dom);//equal to owners {}
    console.log("DOMI:");console.log(domi);//equal to owners
    $.map(dom, function(sub, subi){
        console.log("DOM:");console.log(sub);//equal to subs {}
        console.log("DOMI:");console.log(subi);//equal to subs    
    })       
     return ("<div class='tt_sect "+tvi+"'></div>");
}).join("")

or if you just want to iterate through the sub1 and sub2 you can use this

  $.map(dominant, function(dom, domi){
        console.log("DOM:");console.log(dom);//equal to owners {}
        console.log("DOMI:");console.log(domi);//equal to owners
         $.each(sub, function() {
          console.log("DOM:");console.log(sub);//equal to subs {}           
        });                    
   return ("<div class='tt_sect "+tvi+"'></div>"     
    }).join("")
Comments