开发者

javascript sort object of objects

I have an Object of Objects. (because I want to use associative array, so object of objects, not numeric array of objects)

var tasks=new Object();

for(...){
tasks[foo-i]={};
tasks[foo-i].index=....;
tasks[foo-i].name=...;
}

I have a function that'll output the name of the tasks, but they have to be according to the index in ascending order. So, I'll have to开发者_运维问答 have a temporary sort-function. How would you do that? Thanks


Option 1: Output in order of the keys on the task object:

Perhaps there is a more elegant way, but this way gets all the tasks keys out of the object, sorts them and then uses the ordered index array to cycle through the original object in key order (if I understood correctly what you're trying to do).

var indexArray = [];
var i;
for (i in tasks) {
    indexArray.push(i);   // collect all indexes
}
indexArray.sort(function(a,b) {return(a-b);});  // sort the array in numeric order
for (i = 0; i < indexArray.length; i++) {
    console.log(tasks[indexArray[i]].name);
}

You could use tasks.keys as a shortcut to getting the object indexes, but that is not universally available so you'd have to have an alternate way of doing it anyway.

Option 2: Output in order of the embedded index tasks[i].index:

Reading your question again, I realized that there may be another way to interpret your question. Perhaps you meant in index order where it's the .index data right next to the .name, not the index key on the tasks object. If so, that would take a different routine:

var sorted = [];
var i;
for (i in tasks) {
    sorted.push(tasks[i]);   // collect items from tasks into a sortable array
}
sorted.sort(function(a,b) {return(a.index - b.index);});  // sort the array in numeric order by embedded index
for (i = 0; i < sorted.length; i++) {
    console.log(sorted[i].name);
}


You could stick all names in a temp array and then call the sort() method on that array. Check this link

Regards


You can pass a function to the sort method of the Array object, which is used to determine the order of the objects in the array. By default, it does this alphabetically and numerically but the numerical way is a bit messed up. Here is how I'd solve your case, assuming that the indexes you're using to sort them are numerical:

tasks.sort(function(obj1,obj2){
    return obj1.index - obj2.index;
});

The function passed to the sort method should return a positive integer if object1>object2, 0 if object1=object2, and a negative integer if object1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜