jQuery: Sort results of $.each

2020-02-11 14:24发布

问题:

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 obj = {
    obj1: 39,
    obj2: 6,
    obj3: 'text'
    obj4: 'text'
    obj5: 0
};

I loop through the object like so:

$(array).each(function(index, value) {
    // ...
});

I want to sort by obj3 and obj4. Preferrably not using an asynchronous method, how can I sort the results before (or during) output? (I also don't want to loop through this twice, as there could be hundreds at any given time.

回答1:

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;
});


回答2:

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.