我想在一天内为已经创建了两个或更多对象(createdAt
)的用户遍历所有对象。 (00:00:00 - 23:59:59)一天的纪元:86400秒)。我想在这一天内做这件事,让我们说一年。这有可能吗?如何实现这个目标?
结果可以是在同一天创建了两个或更多对象的用户数组。
我设置了Firebase数据库,其中包含以下结构:
{
"-KFNn8CA5QdxuhJaaatw" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 1
},
-KFNn8CA5QdxuhJW11tw" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 1
},
-KFNn8CA5QdxuhJW66tw" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 3
},
-KFNn8CA5QdxuhJW6123w" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 5
}
.....
}
答案 0 :(得分:4)
这就是我得到的:
var arr = {
"-KFNn8CA5QdxuhJaaatw" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 1
},
"-KFNn8CA5QdxuhJW11tw" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 1
},
"-KFNn8CA5QdxuhJW66tw" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 3
},
"-KFNn8CA5QdxuhJW6123w" : {
"some" : "data",
"createdAt" : 1460704940,
"points" : 0,
"userKey" : 5
}
};
// keeps a reference of the last object a user created
var dict = {};
// using an object, so we get distinct values
var userKeys = {};
// getting a list of objects ordered by creation time
var objs = Object.keys(arr).map(function (k) {
return arr[k];
});
objs.sort(function (a, b) {
return a.createdAt - b.createdAt;
});
objs.forEach(function (obj) {
// if dict holds an object for this user, compare if they were created in the same day
if (dict[obj.userKey]) {
if (inSameDay(dict[obj.userKey].createdAt, obj.createdAt)) {
userKeys[obj.userKey] = true;
}
}
// store the object the user created last
dict[obj.userKey] = obj;
});
// get ids as an array
var users = Object.keys(userKeys);
// compare if two datetimes are in the same day
function inSameDay(t1, t2) {
var d1 = new Date(t1 * 1000);
var d2 = new Date(t2 * 1000);
return d1.getFullYear() == d2.getFullYear() &&
d1.getMonth() == d2.getMonth() &&
d1.getDate() == d2.getDate();
}
最后,users
数组将包含在同一天创建两个对象的用户的键。
如果您希望获得的信息多于您提出的信息,请创建一个按您要查询的数据分组的数据结构,然后很容易获得您想要的任何结果。这是一个例子:
// this is an object containing all the data
// grouped by userKey and date
var data = {}
Object.keys(arr).forEach(function (key) {
var obj = arr[key];
var userData = data[obj.userKey];
if (!userData) {
data[obj.userKey] = (userData = {});
}
var date = new Date(obj.createdAt * 1000);
var dateString = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
var dateData = userData[dateString];
if (!dateData) {
userData[dateString] = (dateData = []);
}
dateData.push(obj);
});
// this is an array of userKeys for users with
// two or more items created per day
var users = Object.keys(data)
.filter(function (userKey) {
var dates = Object.keys(data[userKey]);
for (var i = 0; i < dates.length; i++) {
if (data[userKey][dates[i]].length >= 2)
return true;
}
return false;
});
// and this is their data
var dataOfUsers = {};
users.forEach(function (userKey) {
dataOfUsers[userKey] = data[userKey];
});