How can I use lodash/underscore to sort by multiple nested fields?

前端 未结 7 1159
情话喂你
情话喂你 2021-02-03 21:51

I want to do something like this:

var data = [
    {
        sortData: {a: \'a\', b: 2}
    },
    {
        sortData: {a: \'a\', b: 1}
    },
    {
        sort         


        
7条回答
  •  迷失自我
    2021-02-03 22:37

    I think this could work in most cases with underscore:

    var properties = ["sortData.a", "sortData.b"];
    data = _.sortBy(data, function (d) {
        var predicate = '';
        for (var i = 0; i < properties.length; i++)
        {
            predicate += (i == properties.length - 1 
                               ? 'd.' + properties[i]
                               : 'd.' + properties[i] + ' + ')
        }
        return eval(predicate)
    });
    

    It works and you can see it in Plunker

提交回复
热议问题