这是我的数组:

['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California']


lodash中是否有一种方法可以将其转换为具有重复出现次数的对象,如下所示:

[
    {'name':'California', 'count':2},
    {'name':'Texas', 'count':3},
    {'name':'New York', 'count':1},
    {'name':'Missouri', 'count':1},
    {'name':'New Mexico', 'count':1},
]


我尝试了许多组合,但未成功。文件:https://lodash.com/docs#countBy

最佳答案

您可以映射_.countBy的结果。



var array = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'],
    count = _.countBy(array),
    result = _.map(count, (v, k) => ({ name: k, count: v }));

console.log(count);
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>





_.chain结合



var array = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'],
    count = _
        .chain(array)
        .countBy()
        .map((v, k) => ({ name: k, count: v }));

console.log(count);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

10-07 13:25