javascript sort object of objects

后端 未结 3 793
无人及你
无人及你 2021-01-27 08:06

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(...){
tas         


        
相关标签:
3条回答
  • 2021-01-27 08:41

    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 讨论(0)
  • 2021-01-27 08:43

    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);
    }
    
    0 讨论(0)
  • 2021-01-27 08:55

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

    Regards

    0 讨论(0)
提交回复
热议问题