简体   繁体   English

下划线将对象转换为数组并按键名排序

[英]Underscore convert object to array and sort by key name

I've been using the below code to transform a large list of dates in a array of counts which i can then use in a simple line chart. 我一直在使用下面的代码来转换计数数组中的大日期列表,然后可以在简单的折线图中使用它。 The issue i'm encountering is with sorting the values by the year and week number. 我遇到的问题是按年和周编号对值进行排序。 When i have data such as [{201501: 20},{201502: 20},{201451: 20},{201452: 20}] i need to sort the array by the key name into the following format [{201451: 20},{201452: 20},{201501: 20},{201502: 20}] . 当我拥有[{201501: 20},{201502: 20},{201451: 20},{201452: 20}]我需要按键名将数组排序为以下格式[{201451: 20},{201452: 20},{201501: 20},{201502: 20}] They i simply discard the key with _.values() 他们我只是用_.values()丢弃了键

How do i go about ordering the array with underscore, i've tried a few things but i'm pretty lost at this point. 我要如何对带下划线的数组进行排序,我已经尝试了一些方法,但是此时我还是很迷茫。

    var graphData = _.chain(thisYearFiltered)
    // map each string like '2014-01-01 00:00:00' using moment.js to the ISO Week. ISO weeks are used because they run Monday to Sunday
    .map(function(date){ 
        return moment(date, "YYYY-MM-DD HH:mm:ss").isoWeekYear() + moment(date, "YYYY-MM-DD HH:mm:ss").isoWeek(); 
    })
    // Manipulate weeks numbers [201423,201423,201423,201423,201424] into a count for each like [{201423:4 },{201424:1}]
    .countBy(function(num) {
        //console.log(num);
        return num;
    })
    // Pull out the values of the objects and discard the week number. [{23:4 },{24:1}] to [4,1]
    .values()
    .value();

I know this is all possible with underscore but i've hit a wall with this one so any suggestions would be welcome. 我知道使用下划线是可能的,但是我已经碰到了这个问题,因此欢迎提出任何建议。

I've looked into _.sortBy() but that seems to expect a named key to sort on and in my case the keys names are all different. 我已经研究过_.sortBy()但是似乎希望可以对命名键进行排序,而在我的情况下,键名都是不同的。 Could i do something similar with the first key? 我可以对第一把钥匙做些类似的事情吗?

For objects, sortBy also passes the key to the callback as the second argument and only keeps the value of the object after sorting it, so: 对于对象, sortBy还将键作为第二个参数传递给回调,并且仅在对对象进行排序后保留其值,因此:

_.chain([201423, 201423, 201423, 201423, 201424]).
   countBy(function(n) { return n; }).
   sortBy(function(v, k) { return k; }).
   value()

gives

[ 4, 1 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM