jQuery: Sort results of $.each

前端 未结 2 923
轻奢々
轻奢々 2020-12-18 12:28

The only examples I have been able to find of people using $.each are html samples, and it\'s not what I want. I have the following object:

var          


        
相关标签:
2条回答
  • 2020-12-18 13:17

    Object properties do not have a defined order. They cannot be sorted. Arrays do have order. If you want the keys in a specific order, you will have to put them in an array and define the order.

    You could grab all the property names (e.g. the keys) from the object, sort them and then iterate the properties in that order if you want. To do that, you'd do it like this:

    var obj = {
        obj1: 39,
        obj2: 6,
        obj3: 'text'
        obj4: 'text'
        obj5: 0
    };
    var keys = [];
    for (var prop in obj) {
        keys.push(prop);
    }
    keys.sort();
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var value = obj[key];
        // do whatever you want to do with key and value
    }
    

    As you will see, this requires an extra iteration to obtain and sort the list of keys. I'm not aware of any way around that. Obtaining the keys can be done in a modern browser with obj.keys(), but internally that's probably an iteration through the object properties anyway and you'd need a shim to allow that to work in older browsers.

    0 讨论(0)
  • 2020-12-18 13:24
    var array = {
        obj1: 39,
        obj2: 6,
        obj3: 'text'
        obj4: 'text'
        obj5: 0
    };
    

    is not an array (its name notwithstanding). It is an object. The idea of sorting by obj3 and obj4 doesn't really make sense.

    Now, if you were to convert this object to an array of objects, you could sort that array with the array.sort method.

    var array = [
        { obj1: 39,
          obj2: 6,
          obj3: 'text'
          obj4: 'text'
          obj5: 0
        },{ obj1: 40,
          obj2: 7,
          obj3: 'text2'
          obj4: 'text3'
          obj5: 0
        }
    ];
    
    array.sort(function(a, b) {
    
        var textA = a.obj3.toLowerCase();
        var textB = b.obj3.toLowerCase();
    
        if (textA < textB) 
           return -1; 
        if (textA > textB)
           return 1;
        return 0; 
    });
    

    and of course to sort by a numeric property, it'd simply be:

    array.sort(function(a, b) {
        return a.obj1 - b.obj1;
    });
    
    0 讨论(0)
提交回复
热议问题