I’m attempting to create a simple column view which will allow me to explore nested arrays. The goal is to have a user click on a ‘name’ in the ‘name’ column, and have the corresponding movies list appear in the next column. For example, I’d provide a JSON array like this:
var array = [
{
"name":"sean connery",
"index":0,
"movies": [
{"name": "Goldfinger",
"id": 43},
{"name":"Thunderball",
"id":103}
]
},{
"name":"pierce brosnan",
"index":1,
"movies": [
{"name": "Goldeneye",
"id": 22},
{"name":"The world is not enough",
"id":100}
]
}
]
And basically, I’m kinda cheating in order to retrieve the movies array for the corresponding name. I read the ‘index’ attribute that is appended to the li element, and use that to pick out the appropriate index to retrieve the movies array.
// sorts alphabetically
array.sort(function(a, b) {
return b.name < a.name ? 1 : b.name > a.name ? -1 : 0;
});
$.each(array, function(index, value){
listitem = document.createElement('li');
$(listitem).html(value.name).appendTo($("ul#list")).attr("data-id",value.index);
});
//make it a scrollbox
$("ul#list").scrollTop();
//click to display movies
$("ul#list li").click(function(){
var id = $(this).attr("data-id");
movies = array[id].movies;
console.log(movies);
});
But this doesn’t seem like the ideal method here. It seems like there should be a way to retrieve the appropriate movies array without needing to alter the DOM. Any suggestions? Or am what I’m doing a legit way?
Thanks! and a Fiddle containing my code: http://jsfiddle.net/bmcmahen/WXvWv/2/
You could go even further and attach the whole movie array to the
<li>usingdata:Demo: http://jsfiddle.net/ambiguous/Ug43b/
Or, if that doesn’t make sense in your situation you can use
indexto figure out where the<li>is inside the<ul>and use that to index into the array:You could also cache
$('ul#list li')if you wanted:Demo: http://jsfiddle.net/ambiguous/kbvGf/
Which way you go depends on your specific situation of course. The
indexapproach does require your<ul>to exactly matcharrayand that could be a problem, using a data-attribute nicely sidesteps this problem by binding each<li>directly to a set of movies either directly throughdata-moviesor indirectly through the index indata-id.