javascript 循环访问用户及其登录日期并合并数据集

nmpmafwu  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(78)

我正在尝试构建一些 Jmeter 板组件-我想循环数据,以获得所有用户每天的登录总数。
代码看起来像这样-但需要设置标志,以便在日期(天)更改时截断计数

let people = [{
    "loginHistory": ["2023-04-25T18:00:54.205+00:00", "2023-04-26T18:00:54.205+00:00", "2023-04-26T18:04:54.205+00:00", "2023-04-27T18:00:54.205+00:00"]
  },
  {
    "loginHistory": ["2023-04-22T18:00:54.205+00:00", "2023-04-22T18:00:54.205+00:00", "2023-04-25T18:04:54.205+00:00", "2023-04-27T18:00:54.205+00:00"]
  }
]

//array of people -- with an array of login datestamps

//loop through the users and get a date/count 

let userDateValues = [];
let dateValues = [];

for (let i = 0; i < people.length; ++i) {
  let loginHistory = people[i].loginHistory;
  //sort array by date
  if (loginHistory) {
    for (let j = 0; j < loginHistory.length; ++j) {
      console.log("loginHistory[j]", loginHistory[j]);
    }
  }

  //flags to cut/count the logins per day for this user
  let dateValue = {
    "date": moment(), //unique day
    "value": 10
  }
  dateValues.push(dateValue);

  //add data to array
  userDateValues.push(dateValues);
}

console.log("dateValues", dateValues);
console.log("userDateValues", userDateValues);

//want to then merge ALL the counts per same day - so find out how many times ALL users had logged in each day

/*    
[{
    "date": moment(),
    "value": 10
  }, {
    "date": moment().add(1, 'days'),
    "value": 612
  }, {
    "date": moment().add(2, 'days'),
    "value": 23
  }, {
    "date": moment().add(3, 'days'),
    "value": 23
  }]
*/
y1aodyip

y1aodyip1#

如果这不是一个很大的表,我会选择下面的方法,虽然效率不是很高,但它很简单,可读性很强。
1.将所有日期“平铺”到一个仅包含日期的数组中
1.使用循环,创建一个对象,其中键是日期(不是时间戳,只有日期部分),值是存在的次数
1.将对象转换为数组。(数组{Date,Count})
1.按天排序数组

let people = [{
    "loginHistory": ["2023-04-25T18:00:54.205+00:00", "2023-04-26T18:00:54.205+00:00", "2023-04-26T18:04:54.205+00:00", "2023-04-27T18:00:54.205+00:00"]
  },
  {
    "loginHistory": ["2023-04-22T18:00:54.205+00:00", "2023-04-22T18:00:54.205+00:00", "2023-04-25T18:04:54.205+00:00", "2023-04-27T18:00:54.205+00:00"]
  },
  {
    "loginHistory": ["2023-04-22T18:00:54.205+00:00", "2023-04-22T18:00:54.205+00:00", "2023-04-25T18:04:54.205+00:00", "2023-04-27T18:00:54.205+00:00"]
  }
];

//flat all the dates to one array
const timestamps = people.flatMap(_ => _.loginHistory);

//count the occurences of each date in a dictionary structure
const day2count = {};
timestamps.forEach(timestamp => {
    const day = timestamp.split('T')[0];
    day2count[day] = (day2count[day] || 0) + 1;
});
   
// convert the map to an array of entries

const result = Object.entries(day2count).map(([date, count]) => ({Date: date, Count: count }))
    // The date format is already sortable, so we can just sort the entries by key
    .sort((a, b) => a.Date.localeCompare(b.Date))

console.log(JSON.stringify(result, null, 2));

相关问题