2

我在 Javascript 中有一系列类似于以下内容的项目:

var data =
[
{"id":"338b79f07dfe8b3877b3aa41a5bb8a58","date":"2000-10-05T13:21:30Z","value":  {"country":"United States"}},
{"id":"338b79f07dfe8b3877b3aa41a5bb983e","date":"2000-02-05T13:21:30Z","value":{"country":"Norway"}},
{"id":"338b79f07dfe8b3877b3aa41a5ddfefe","date":"2000-12-05T13:21:30Z","value":{"country":"Hungary"}},
{"id":"338b79f07dfe8b3877b3aa41a5fe29d7","date":"2000-05-05T13:21:30Z","value":{"country":"United States"}},
{"id":"b6ed02fb38d6506d7371c419751e8a14","date":"2000-05-05T18:15:30Z","value":{"country":"Germany"}},
{"id":"b6ed02fb38d6506d7371c419753e20b6","date":"2000-12-05T18:15:30Z","value":{"country":"Hungary"}},
{"id":"b6ed02fb38d6506d7371c419755f34ad","date":"2000-06-05T18:15:30Z","value":{"country":"United States"}},
{"id":"b6ed02fb38d6506d7371c419755f3e17","date":"2000-04-05T22:15:30Z","value":{"country":"Germany"}},
{"id":"338b79f07dfe8b3877b3aa41a506082f","date":"2000-07-05T22:15:30Z","value":{"country":"United Kingdom"}},
{"id":"9366afb036bf8b63c9f45379bbe29509","date":"2000-11-05T22:15:30Z","value":{"country":"United Kingdom"}}
];

我需要按日期查询(减少)数组。大于或小于预定日期,例如。当前日期。

我正在考虑使用下划线减少方法来做到这一点。任何人都可以提供我如何做到这一点的例子吗?

编辑:我尝试这样的事情:

var itemsByDate = _(items).reduce(function(memo, item) {
memo[item.date] = memo[item.date] || [];
memo[item.date].push(item);
return memo;
}, {});

console.log((JSON.stringify(itemsByDate["2000-11-05T22:15:30Z"])));​

但这会寻找精确匹配,并且可能无法正确处理日期,因为它们是字符串。

问候,

卡尔斯基

4

1 回答 1

1

如果要过滤集合,可以这样做:

var reduced = data.filter(function(obj) {
    var date = +(new Date(obj.date));
    return date < someDate || date > someOtherDate
});

如果你想把它减少到一对集合,你可以这样做:

var now = Date.now();

var reduced = data.reduce(function(ret, obj) {
    var date = +(new Date(obj.date));
    if (date < now)
        ret.before.push(obj);
    else
        ret.onOrAfter.push(obj);
    return ret;
}, {before:[], onOrAfter:[]});
于 2012-10-08T18:42:42.220 回答