如何使用lodash / underscore按多个嵌套字段排序? [英] How can I use lodash/underscore to sort by multiple nested fields?

查看:287
本文介绍了如何使用lodash / underscore按多个嵌套字段排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

var data = [
    {
        sortData: {a: 'a', b: 2}
    },
    {
        sortData: {a: 'a', b: 1}
    },
    {
        sortData: {a: 'b', b: 5}
    },
    {
        sortData: {a: 'a', b: 3}
    }
];

data = _.sortBy(data, ["sortData.a", "sortData.b"]);

_.map(data, function(element) {console.log(element.sortData.a + " " + element.sortData.b);});

并输出此信息:

"a 1"
"a 2"
"a 3"
"b 5"

不幸的是,这不起作用,数组仍以原始形式排序。 如果字段未嵌套在 sortData 中,则可以使用。如何使用lodash / underscore按多个嵌套字段对对象数组进行排序?

Unfortunately, this doesn't work and the array remains sorted in its original form. This would work if the fields weren't nested inside the sortData. How can I use lodash/underscore to sort an array of objects by more than one nested field?

我已将此转换为lodash功能请求: https://github.com/lodash/lodash/issues/581

I've turned this into a lodash feature request: https://github.com/lodash/lodash/issues/581

推荐答案

lodash版本3中有 _。sortByAll 方法:

There is a _.sortByAll method in lodash version 3:

https: //github.com/lodash/lodash/blob/3.10.1/doc/README.md#_sortbyallcollection-iteratees

Lodash第4版,它有统一:

Lodash version 4, it has been unified:

https://lodash.com/ docs#sortBy

其他选项是对值进行排序自己:

Other option would be to sort values yourself:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

function compareValues(v1, v2) {
    return (v1 > v2) 
        ? 1 
        : (v1 < v2 ? -1 : 0);
};


var data = [
    { a: 2, b: 1 },
    { a: 2, b: 2 },
    { a: 1, b: 3 }
];

data.sort(function (x, y) {
    var result = compareValues(x.a, y.a);

    return result === 0 
        ? compareValues(x.b, y.b) 
        : result;
});

// data after sort:
// [
//     { a: 1, b: 3 },
//     { a: 2, b: 1 },
//     { a: 2, b: 2 }
// ];

这篇关于如何使用lodash / underscore按多个嵌套字段排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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