首先,然后使用lodash根据名称对数组进行排序?

时间:2018-06-27 00:11:47

标签: javascript lodash

我有一些json,格式为:

data = { 
    "1": {"name": "eve", "type": "sergeant", "age": 22},
    "2": {"name": "bob", "type": "sergeant", "age": 33},
    "3": {"name": "bats", "type": "private", "age": 90},
    "4": {"name": "carol", "type": "captain", "age": 50},
    "5": {"name": "noogle", "type": "sergeant", "age": 34},
    "6": {"name": "good", "type": "sergeant", "age": 47},
    "7": {"name": "alice", "type": "private", "age": 34}
}

如何groupBy type,然后在每种类型中按名称升序对它们进行排序

我试图这样做:

let grouped = _.groupBy(Object.keys(data), function(id) {
    return data[id].type;
});

哪个会给我类似的东西

{
    "sergeant": ["1", "2", "5", "6"],
    "private": ["3", "7"],
    "captain": ["4"]
}

但是当我尝试sortBy时,它给了我与上面相同的对象:

_.map(Object.keys(grouped), function(type_name) {
    grouped[type_name] = _.sortedBy(grouped[type_name], function(id) {
        return data[id].name;
    });
});

将对象分组在一起后如何排序数组?有没有一种方法可以将groupBysortBy整齐地链接在一起,而不是像上面那样拆分逻辑?

1 个答案:

答案 0 :(得分:2)

使用_.mapValues对每个组进行分组后,可以使用_.groupBy方法对每个组进行排序。只需获取每个值,然后在您的_.mapValues回调函数中返回它的排序版本即可。

示例:

data = { 
    "1": {"name": "eve", "type": "sergeant", "age": 22},
    "2": {"name": "bob", "type": "sergeant", "age": 33},
    "3": {"name": "bats", "type": "private", "age": 90},
    "4": {"name": "carol", "type": "captain", "age": 50},
    "5": {"name": "noogle", "type": "sergeant", "age": 34},
    "6": {"name": "good", "type": "sergeant", "age": 47},
    "7": {"name": "alice", "type": "private", "age": 34}
}

console.log(_.mapValues(_.groupBy(data, "type"), v => _.sortBy(v, "name")))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

或者,如果只希望对键进行分组和排序,或者对键/值进行分组和排序,尽管看起来并不那么容易,但是可以使用相同的方法:

data = { 
    "1": {"name": "eve", "type": "sergeant", "age": 22},
    "2": {"name": "bob", "type": "sergeant", "age": 33},
    "3": {"name": "bats", "type": "private", "age": 90},
    "4": {"name": "carol", "type": "captain", "age": 50},
    "5": {"name": "noogle", "type": "sergeant", "age": 34},
    "6": {"name": "good", "type": "sergeant", "age": 47},
    "7": {"name": "alice", "type": "private", "age": 34}
}

// If all you want are grouped and sorted keys:
console.log(_.mapValues(_.groupBy(_.keys(data), k => data[k].type), v => _.sortBy(v, i => data[i].name)))

// Or for grouped and sorted keys and values:
console.log(_.mapValues(_.groupBy(_.keys(data), k => data[k].type), v => _.sortBy(v, i => data[i].name).map(k => ({[k]: data[k]}))))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>