且构网

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

如何按嵌套对象属性对 JavaScript 对象数组进行排序?

更新时间:2022-11-16 13:17:15

您可以在 . 上拆分 prop,并迭代 Array 更新 ab 在每次迭代期间具有下一个嵌套属性.

You can split the prop on ., and iterate over the Array updating the a and b with the next nested property during each iteration.

示例: http://jsfiddle.net/x8KD6/1/一个>

var sort = function (prop, arr) {
    prop = prop.split('.');
    var len = prop.length;

    arr.sort(function (a, b) {
        var i = 0;
        while( i < len ) { a = a[prop[i]]; b = b[prop[i]]; i++; }
        if (a < b) {
            return -1;
        } else if (a > b) {
            return 1;
        } else {
            return 0;
        }
    });
    return arr;
};