元芳怎么了
将 jsonData 数组作为摘要函数的输入传递。function groupByRegistrationDate(array) { const months = [ "Jan", "Feb", "March", "April", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec" ]; return array.reduce((agg, current) => { const { registration_time, sex } = current; const month = months[new Date(registration_time).getMonth()]; (agg[month] = agg[month] || []).push(sex.toLowerCase()); return agg; }, {});}function preprocess(data) { return data.map((entry) => entry.data);}function summarize(jsonData) { const aggregatedData = groupByRegistrationDate(preprocess(jsonData)); Object.entries(aggregatedData).forEach(([month, registrations]) => { const maleRegs = registrations.filter(x => x === 'male').length; const femaleRegs = registrations.length - maleRegs; console.log(`${month} - Male ${maleRegs} Female ${femaleRegs}`); });}summarize(jsonData);
汪汪一只猫
global.fetch = require("cross-fetch");fetch("https://pastebin.com/raw/fvJkWEk5") .then(response => { return response.json(); }) .then(data => { var months = [ "Jan", "Feb", "March", "April", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec" ]; var data = data.map(users => { var subset = { registration_time: users["data"]["registration_time"], sex: users["data"]["sex"] }; var sex = subset["sex"]; var date = new Date(subset["registration_time"]); var m = date.getMonth(); return {month: m, sex: sex}; }); var uniqueMonths = []; var monthlyData = []; data.map(x => { if(typeof uniqueMonths.find(m => m.month === x.month) === 'undefined') { uniqueMonths.push({month: x.month, female: 0, male: 0}); } monthlyData.push({ month: x.month, female: x.sex === 'Female' ? 1: 0, male: x.sex === 'Male' ? 1: 0 }); }); uniqueMonths = uniqueMonths.sort((a, b) => a.month-b.month); uniqueMonths.map(m => { monthlyData.filter(d => d.month === m.month).map(x => { m.female += x.female; m.male += x.male; }); console.log(`${months[m.month]} - male ${m.male} female ${m.female}`); }); }) .catch(err => { console.error(err); });
ITMISS
要以上述给定格式打印数据,请使用此选项,其中json_data是您的 JSON 对象var months = [ "Jan", "Feb", "March", "April", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec" ]; var months_data = [ { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, { "female" : 0, "male" : 0, }, ] json_data.map((u,i) => { months_data[parseInt(u.data.registration_time.split("-")[1]) - 1][u.data.sex.toLowerCase()]++; }) months_data.map((u,i) => { console.log(months[i] + " male " + u.male + " female " + u.female); })