Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an object in javascript with an unordered index

I'm creating a playlist system where each song has a unique ID. When you add a song to the playlist array, its index is registered as its ID.

Normally when looping over a javascript array, you grab the length and count up through the index. Is there a way to loop through an array with unused indexes? Is that bad practice for any reason?

like image 585
c.. Avatar asked Sep 24 '11 16:09

c..


2 Answers

var obj = {"123": "Lalala",
           "456": "dum dum"};
for(var i in obj){
    //i = ID
    // obj[i] = "song"
}

Use for(var i in obj) to loop through an object. See the comments above to understand the meaning of this for-statement.

You're talking about Objects, not arrays, by the way:

var array = [7, 5, 9];

An array can be simulated in this way, so that a for(var i=0; i<array_like.length; i++) can be used. Array functions (such as pop) cannot be used on them, unless you define it:

var array_like = {0:7, 1:5, 2:9, length:3};
like image 162
Rob W Avatar answered Nov 14 '22 21:11

Rob W


You can access the object's properties one of two ways. Either using a "." such as:

var my prop = obj.property;

Or via bracket notation:

var my prop = obj["property"];

Now, that doesn't really answer your question. So, here are a few ways:

Utilize jQuery's each function:

$.each(obj, function(key, value){
    //Do something with your key and value.
});

Utilize the Javascript for function:

for(var key in obj)
{
    var value = obj[key];
    //Do something with your key and value.
}

Hope that helps!

like image 38
Jonathan Avatar answered Nov 14 '22 22:11

Jonathan