javascript - Is it possible to access children of an object w/out knowing the parent? -
i have object:
[ {"ml":[ {"teamname":"team 1","league":"league 1"}, {"teamname":"team 2","league":"league 2"}, {"teamname":"team 3","league":"league 3"} ]}, {"3a":[ {"teamname":"team 4","league":"league 1"}, {"teamname":"team 5","league":"league 2"}, {"teamname":"team 6","league":"league 3"} ]}, {"2a":[ {"teamname":"team 7","league":"league 1"}, {"teamname":"team 8","league":"league 2"}, {"teamname":"team 9","league":"league 3"} ]} ] how can access "teamname" each grouping without specifying parent (e.g. "ml")?
normally, it's ml.teamname, possible x.teamnname?
the reason grouping names dynamic , unpredictable.
i want iterate through groups (parent groups w/ children set within them). think of creating <ul> each grouping (w/ name of grouping title) , list of children in <li> has value of "teamname".
i'm using jquery , want results this:
<h4>ml</h4> <ul> <li>team 1</li> <li>team 2</li> <li>team 3</li> </ul> <h4>3a</h4> <ul> <li>team 4</li> <li>team 5</li> <li>team 6</li> </ul> <h4>2a</h4> <ul> <li>team 7</li> <li>team 8</li> <li>team 9</li> </ul>
if object stored in data, can utilize es5 map:
data.result.map(function(obj){ for(var in obj) if(obj.hasownproperty(i)) homecoming obj[i].map(function(obj){ homecoming obj.teamname }); }); or simplifying es6 arrow functions:
data.result.map(obj => { for(var in obj) if(obj.hasownproperty(i)) homecoming obj[i].map(obj => obj.teamname); }); with little modifications, can html (note it's vulnerable html injection)
wrapper.innerhtml += data.result.map(obj => { for(var in obj) if(obj.hasownproperty(i)) homecoming '<h4>'+i+'</h4>\n' + obj[i].map(obj => '\t<li>'+obj.teamname+'</li>\n').join(''); }).join(''); this way isn't vulnerable:
data.result.foreach(obj => { for(var in obj) if(obj.hasownproperty(i)) { var h4 = document.createelement('h4'), ul=document.createelement('ul'); h4.appendchild(document.createtextnode(i)); wrapper.appendchild(h4); obj[i].foreach(obj => { var li = document.createelement('li'); li.appendchild(document.createtextnode(obj.teamname)); ul.appendchild(li); }); wrapper.appendchild(ul); return; } }) javascript arrays json
No comments:
Post a Comment