...

View Full Version : Sort objects by property



grogo21
03-21-2012, 07:44 AM
Hello, I have the following object:




var layers = {
photo1 : {
index : 1,
xPos : 63,
yPos : 48,
angle : 0
},
background : {
index : 0,
xPos : 278,
yPos : 163,
angle : 0
}
}



How can I sort the objects by the index property?



for(var layer in layers.sort(???))
{
}


Thx Very Much!

glenngv
03-21-2012, 08:27 AM
Put each object in an array then you can use array's sort() method.


var arr = [];
for (var i in layers) {
arr.push(layers[i]);
}
arr.sort(function(a, b){
return a.index - b.index;
});
//test it
for (var i in arr){
alert(arr[i].index);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum