我无法理解以下内容,希望有人能把我送到正确的方向。
对于社交媒体分析,我想创建一个散点图,显示您每天和每小时收到的喜欢的数量,以便您可以了解发布到社交媒体的好时机。
我得到了一个对象数组,其中包含每个帖子的所有信息,例如:day(0-6),小时(0-23),喜欢的数量。看起来像这样:
var posts_array = [{caption: "hello", day: 0, hours: 2 ,likes:200},
{caption: "hello2", day: 0, hours: 1, likes: 100}];
为了绘制散点图,我需要得到一个如下所示的对象数组:
var array_objects = [{day: 0, hours:0, sum_of_likes: somenumber},{day:0,
hours:1, sum_of_likes: somenumber}]
我的计划是创建一个包含日,小时和总和的对象数组。然后遍历每个帖子,日和小时,并将喜欢的数量添加到正确的对象。
到目前为止,我得到了这个:
//create array of objects for each day and hour
var array_objects = [];
for (var i = 0; i < 7; i++) {
for (var j = 0; j < 24; j++) {
var object = new Object();
object.day = i;
object.likes = 0;
object.timeslot = j;
array_objects.push(object);
}
}
//loop through each day and hours
for (var i = 0; i < posts_array.length; i++) { //loop through all posts
for (var j = 0; j < 7; j++) { //loop through each day
if (posts_array[i].day == j){
for (var k = 0; k < 24; k++) { //loop through each hour of day
if(posts_array[i].hours == k){
//how to get object reference?
}
}
}
}
}
但我很难在最后找到对象的引用。我也想知道这是否是正确的方法,因为它似乎有点乏味的做法。
答案 0 :(得分:1)
随着时间的推移组合数据会更容易。您可以为此目的创建字典字典。
array_objects = {}
for (var i = 0; i < posts_array.length; i++) {
var temp = post_array[i]
if array_objects[temp.day+"_"+temp.hours] {
array_objects[temp.day+"_"+temp.hours][sum_of_likes] += temp.likes
} else {
array_objects[temp.day+"_"+temp.hours] = {day: temp.day, hours: temp.hours, sum_of_likes: temp.likes}
}
}
答案 1 :(得分:0)
好吧,因为你的array_objects是1维并且按照你的方式,你可以这样做:
if(posts_array[i].hours == k){
var reference = array_objects[j * 24 + k];
}
仍然,它做得更好:
for (var i = 0; i < posts_array.length; i++) {
var reference = array_objects[posts_array[i].day * 24 + posts_array[i].hours];
}
答案 2 :(得分:0)
为了解决这个问题,我建议如下:
let scatter_objects = [];
Array.prototype.forEach.call(post_array, (post)=>{
let keys = Object.keys(post);
keys.forEach((key, index, array)=>{
// the arguments are passed for each post object; array is the original post object
// here key is the property like day, hour, likes
// you can now filter each post by key and return an object that
// the end result would be a filtered object pushed to the
// scatter_objects array
// at the end,
scatter_objects.push(processed_object);
});
});