根据对象日期的年份将对象数组拆分成新的数组 [英] Split array of objects into new arrays based on year of object's date
问题描述
我有一个名为 objarray 的对象数组。每个对象如下所示:
var object = {
age:45
coords: -37.807997 144.705784
日期:2002年7月28日00:00:00 GMT + 1000(EST)
}
( date 是一个Date对象)
我需要将每个对象按照日期。我想要最终的结果如下所示:
var dateGroups = [[object,object,object],[object,object ],[object,object,object]];
dateGroups 中的每个数组都包含相同日期的对象。 >
这可能与数组有关吗?以前,我生成了一个新对象,其中包含按日期分组的所有 objarray 对象(从数据生成的日期):
var alldates = {
1991:[object,object,object],
1992:[object,object],
// etc ...
}
上面看起来似乎是一个奇怪的解决方案,但我只需要能够按年份访问对象:ie dateGroups [0] =第一年的对象数组
我将如何获取数据 dateGroups 数组?有没有更好的方式存储这种类型的数据?
考虑使用 Underscore.js groupBy 功能,其次是 sortBy 。
groupBy
将生成一个结构,如 alldates
,如果你这样打电话:
var alldates = _.groupBy(objarray,function(obj){
return obj.date.getFullYear();
});
sortBy
可用于简单排序关键,像这样:
var dateGroups = _.sortBy(alldates,function(v,k){return k;}) ;
您也可以组合这样的两个:
var dateGroups = _.chain(objarray)
.groupBy(function(obj){return obj.date.getFullYear();})
.sortBy (function(v,k){return k;})
.value();
根据您的用例,我可以看到使用阵列数组或对象映射的原因的阵列。如果您正在查找索引,请务必使用以后。
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 is a Date object)
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]];
Each array within dateGroups contains objects with the same date.
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...
}
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
How would I get the data into something like the dateGroups array? Is there a better way to store this type of data?
Consider using the Underscore.js groupBy function, followed by sortBy.
groupBy
will produce a structure like alldates
, if you call it like so:
var alldates = _.groupBy(objarray, function(obj) {
return obj.date.getFullYear();
});
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屋!