如何按嵌套对象属性对 JavaScript 对象数组进行排序? [英] How to sort a JavaScript array of objects by nested object property?

查看:34
本文介绍了如何按嵌套对象属性对 JavaScript 对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数可以根据属性对 JavaScript 对象数组进行排序:

I have this function to sort a JavaScript array of objects based on a property:

// arr is the array of objects, prop is the property to sort by
var sort = function (prop, arr) {
    arr.sort(function (a, b) {
        if (a[prop] < b[prop]) {
            return -1;
        } else if (a[prop] > b[prop]) {
            return 1;
        } else {
            return 0;
        }
    });
};

它适用于这样的数组:

sort('property', [
    {property:'1'},
    {property:'3'},
    {property:'2'},
    {property:'4'},
]);

但我也希望能够按嵌套属性进行排序,例如:

But I want to be able to sort also by nested properties, for example something like:

sort('nestedobj.property', [
    {nestedobj:{property:'1'}},
    {nestedobj:{property:'3'}},
    {nestedobj:{property:'2'}},
    {nestedobj:{property:'4'}}
]);

然而这是行不通的,因为不可能像object['nestedobj.property']那样做,它应该是object['nestedobj']['property'].

However this doesn't work because it is not possible to do something like object['nestedobj.property'], it should be object['nestedobj']['property'].

你知道我怎样才能解决这个问题并使我的函数与嵌套对象的属性一起工作吗?

提前致谢

推荐答案

您可以在 . 上拆分 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;
};

这篇关于如何按嵌套对象属性对 JavaScript 对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆