views:

48

answers:

2

I have an application that creates a playlist of videos and returns them in json format, the video ID is the "key" and then it has video information attached to it. The video ID is not sequential, "1234", "4234", "123", "5454" are possible IDs, among others.

I have a button for switching the next video, the problem is I don't know how to get the next item in the array unless I loop through the entire array which seems very inefficient. I'm using jQuery so if there's a function available that'd be excellent.

A summary of my question: How do I efficiently select the next item in an array using jQuery/javascript?

+1  A: 

If you're in control of the part creating the JSON, I'd change it to actually return an array. If not, I'd probably loop through the object you've created from your JSON data once, creating an array:

var list, name;
list = [];
for (name in obj) {
    list.push({
        key: name,
        value: obj[name]
    });
}

Then you can walk through with a numeric index. Now, there I've retained the name/key. If you don't need that, if you just need the value, the array can just hold the values directly.


Edit Ah, good, you're in control of the JSON. Then I would output the JSON like this:

{
    videos: [
        "1234",
        "4234",
        "123",
        "5454"
    ]
}

Once deserialized, that will result in an object with the property videos which is an array. You can then loop through the array with a numeric index, so the "next video" function would be:

function showNextVideo(videos, index) {
    ++index;
    if (index >= videos.length) {
        index = 0;
    }
    showVideo(videos[index]);
}

You can read more about JSON here: http://json.org

T.J. Crowder
Yes, I create the JSON. How would you recommend I change it to returning an array, is that just modifying the way my JSON is formatted or something more? Do you have any more information that you could link me to? Thanks!
@user265331: I've updated the answer.
T.J. Crowder
A: 

As you don't provide any code, this is more a general answer:

Save the index of the video you are currently playing. As it probably starts with first video in the array, the index is 0, e.g.:

var current = 0;

Now, whenever you click some next button, you increase the index and get the corresponding video:

current++;
video = videos[current];
Felix Kling