对象到新阵列的拆分阵列基于对象的日期的年份 [英] Split array of objects into new arrays based on year of object's date
问题描述
我有对象的数组名为 objarray 。每个对象看起来是这样的:
I have an array of objects called objarray. Each object looks like this:
var object = {
age: "45"
coords: "-37.807997 144.705784"
date: Sun Jul 28 2002 00:00:00 GMT+1000 (EST)
}
(日期为Date对象)
我需要每个对象推到基于日期的新数组。我想最终的结果看起来是这样的:
I need to push each object into a new array based on the date. I want the end result to look like this:
var dateGroups = [[object, object, object],[object, object], [object, object, object]];
dateGroups中的每个阵列包含相同日期的对象。
这是可以做到使用数组? previously我产生含有一个新的对象都在 objarray 按日期(从数据生成的日期)组合的对象:
Is this possible to do with arrays? Previously I generated a new object which contained all the objarray objects grouped by date (dates generated from the data):
var alldates = {
"1991" : [object, object, object],
"1992" : [object, object],
//etc...
}
上面似乎是在实践中一个奇怪的解决方案,不过,我只需要能够在今年访问对象:即 dateGroups [0] =从第一年的对象数组
The above seems like a weird solution in practice though, I only need to be able to access the objects by year: i.e. dateGroups[0] = array of objects from the first year
我如何将获取数据变得像在 dateGroups 数组?有没有更好的方式来存储这种类型的数据?
How would I get the data into something like the dateGroups array? Is there a better way to store this type of data?
推荐答案
考虑使用 Underscore.js 的groupBy 功能,其次是 sortBy 一>
Consider using the Underscore.js groupBy function, followed by sortBy.
GROUPBY
将产生类似的 alldates
的结构,如果你调用它像这样:
groupBy
will produce a structure like alldates
, if you call it like so:
var alldates = _.groupBy(objarray, function(obj) {
return obj.date.getFullYear();
});
sortBy
可用于简单的排序键,这样的:
sortBy
can be used to simply sort by key, like this:
var dateGroups = _.sortBy(alldates, function(v, k) { return k; });
您也可以将二者结合起来是这样的:
You can also combine the two like this:
var dateGroups = _.chain(objarray)
.groupBy(function(obj) { return obj.date.getFullYear(); })
.sortBy(function(v, k) { return k; })
.value();
根据您的使用情况下,我可以看到原因使用数组的数组,数组或一个对象映射。如果你在指数往上看,肯定是使用更高版本。
Depending on your use case, I can see reasons for using an array of arrays, or an object map of arrays. If you're looking up on index, definitely use the later.
这篇关于对象到新阵列的拆分阵列基于对象的日期的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!