且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过键值对Json数组重新排序

更新时间:2023-11-27 10:51:52

JavaScript中的对象本质上不是顺序的.如果您有一个数组,则可以使用它.否则,您必须自己将对象的外部部分转换为数组:

Objects in JavaScript are not ordinal by nature. If you have an array, you can work with that. Otherwise, you have to convert the outer part of the object into an array yourself:

var arrayOfObj = [];

for (item in obj) {
    if (obj.hasOwnProperty(item)) {
        arrayOfObj.push(obj[item]);
    }
}

如果您可以在之前做到这一点,那么您甚至可以获得JSON,那就更好了.一旦有了,就可以使用常规数组.sort方法

If you can do that before you even get the JSON, so much the better. Once you have that, you can just use the normal array .sort method

arrayOfObj.sort(function (a, b) {
    if (a.displayName < b.displayName) {
        return -1;
    }
    else if (a.displayName > b.displayName) {
        return 1;
    }
    return 0;
});

http://jsfiddle.net/ZcM7W/