How to sort a Javascript object, or convert it to an array?

前端 未结 7 574
囚心锁ツ
囚心锁ツ 2020-12-13 04:13

I have some JSON data that I get from a server. In my JavaScript, I want to do some sorting on it. I think the sort() function will do what I want.

However, it seems

7条回答
  •  隐瞒了意图╮
    2020-12-13 04:43

    Array.prototype.slice.call(arrayLikeObject)

    is the standard way to convert and an array-like object to an array.

    That only really works for the arguments object. To convert a generic object to an array is a bit of a pain. Here's the source from underscore.js:

    _.toArray = function(iterable) {
        if (!iterable)                return [];
        if (iterable.toArray)         return iterable.toArray();
        if (_.isArray(iterable))      return iterable;
        if (_.isArguments(iterable))  return slice.call(iterable);
        return _.values(iterable);
    };
    
    _.values = function(obj) {
        return _.map(obj, _.identity);
    };
    

    Turns out you're going to need to loop over your object and map it to an array yourself.

    var newArray = []
    for (var key in object) {
        newArray.push(key);
    }
    

    You're confusing the concepts of arrays and "associative arrays". In JavaScript, objects kind of act like an associative array since you can access data in the format object["key"]. They're not real associative arrays since objects are unordered lists.

    Objects and arrays are vastly different.

    An example of using underscore:

    var sortedObject = _.sortBy(object, function(val, key, object) {
        // return an number to index it by. then it is sorted from smallest to largest number
        return val;
    });
    

    See live example

提交回复
热议问题