如何在Javascript中循环遍历对象并按时间戳进行分类

How do I loop through objects and categorize by timestamps in Javascript?

本文关键字:时间戳 分类 对象 遍历 Javascript 循环      更新时间:2023-09-26

我有一个对象数组,其中有一个名为timestampmotion的键。motion包含一个值,timestamp包含一个unix时间戳。我想迭代多个对象,找到它们对应的"一天中的时间"周期,然后我想合计一天中给定时间的运动值,并将整个值保存在数组中。我希望持续时间是可变的。

假设这些是我的物品;

 {
    timestamp: 1397160634,
    motion: 2,
    id: '534771d8c311731e21c75c9f'
 },
 {
    timestamp: 1397160634,
    motion: 3,
    id: '534771d8c311731e21c75c9f'
 }

现在我创建我的结果数组

var sampleDuration = 60; // Min
var minutesInDay = 1440;
var samplesPerDay = minutesInDay/sampleDuration;
var finalResultItem = []
for (var i = 0; i < samplesPerDay; i++) {
    var IndividualresultArray = []
    IndividualresultArray.push(60*i);
    IndividualresultArray.push(0);
    finalResultItem.push(IndividualresultArray);
}

我现在有一个数组数组,每个子数组的第一个项是一个数字(对应于分钟戳),第二个值是零。

我现在想循环浏览我的所有对象,并根据时间戳中的时间范围增加第二个值(motion

_forEach(objects, function (object) {
{
// grab the timestamp
// figure out which minute range it coresponds to
// increment the array value that corresponds to the minute stamp
// rinse and repeat
}

这是我空白的地方,我需要最终结果看起来像这个

[[30, 5],[60, 20],[90, 5],[120, 0] .........]

或者它甚至可能看起来像这个

[[000002400, 5],[000003000, 20],[000003600, 5],[000004200, 0] .........]

其中第一个值是一个时间戳,它忽略年、月和日,只考虑一天中的时间。

我曾考虑过在一定程度上使用moment.js,但我不确定如何使用。对这个问题有任何帮助都会很好。

我为您创建了一个jsFiddle。运动增量逻辑应该看起来像(我在这里使用jQuery,但你明白了)
// Loop through and increment motion
$.each(objs, function (idx, obj) {
    var date = new Date(obj.timestamp * 1000); // Convert to milliseconds
    var minutesInDay = date.getUTCHours() * 60 + date.getUTCMinutes(); // Remove UTC for local time!
    var minuteRange = Math.floor(minutesInDay / sampleDuration);
    finalResultItem[minuteRange][1] += obj.motion;
});

编辑:在编辑后删除了一些讨论。我还使用了基于sampleDuration的更通用的逻辑。

这应该做到:

_forEach(objects, function (object) {
    var date = new Date(objec.timestamp*1000);
    var minuteOfDay = date.getUTCHours()*60+date.getUTCMinutes();
    finalResultItem[minuteOfDay][1] += object.motion;
})

对于可变采样率,使用secondOfDay并将其除以sampleDuration,然后对其求底以获得数组索引。