mongodb JSON数据来计算总出勤率的百分比?

s3fp2yjn  于 2023-04-20  发布在  Go
关注(0)|答案(3)|浏览(134)

我有一个特定的学生的出勤数据。如果他在场,然后标记1其他标记0在尊重的主题。我如何计算出它的总出勤率。请帮助我...

{
      "CGMM": {
        "17:4:2023": 1,
        "19:4:2023": 0
      },
      "CNS": {
        "17:4:2023": 1
      },
      "ML": {
        "17:4:2023": 1,
        "16:4:2023": 1
      }
    }

我需要我可以计算所有那些值等于1的键值对,然后将其除以总数。

const attendenceInML = Object.keys(student.ML).length;
        const attendenceInSEA = Object.keys(student.SEA).length;
        const attendenceInCGMM = Object.keys(student.CGMM).length;
        const attendenceInCNS = Object.keys(student.CNS).length;
        const total = attendenceInML+ attendenceInSEA+ attendenceInCGMM+ attendenceInCNS;

然后将结果乘以100,得到总出勤率的百分比,但我不知道如何只获取值为1的键值对计数。请帮助我。

bttbmeg0

bttbmeg01#

您可以使用Object.entriesObject.values.reduce的组合来实现

let student = {
      "CGMM": {
        "17:4:2023": 1,
        "19:4:2023": 0
      },
      "CNS": {
        "17:4:2023": 1
      },
      "ML": {
        "17:4:2023": 1,
        "16:4:2023": 1
      }
    }
    
    
let result = Object.entries(student)
               .reduce((prev, [key, objValue]) => prev + Object.values(objValue)
               .reduce((prev,curr) => prev + curr,0),0)

console.log(result)
jqjz2hbq

jqjz2hbq2#

这种格式非常糟糕,但你仍然可以使用for in语法迭代对象:

const data = JSON.parse(input);

let totalClasses = 0;
let attendedClasses = 0;

for (const subject in data) {
  if (data.hasOwnProperty(subject)) { //So that we don't get a runtime error if the object is empty
    const dates = data[subject];
    for (const date in dates) {
      if (dates.hasOwnProperty(date)) {
        totalClasses++;
        attendedClasses += dates[date];
      }
    }
  }
}

const attendancePercentage = (attendedClasses / totalClasses) * 100;
mnemlml8

mnemlml83#

您可以reduce数据并计算总和/平均值。类似于:

const data = {
  "CGMM": {
    "17:4:2023": 1,
    "19:4:2023": 0
  },
  "CNS": {
    "17:4:2023": 1
  },
  "ML": {
    "17:4:2023": 1,
    "16:4:2023": 1
  }
};
const totalAttendance = Object.values(data)
  .reduce( (acc, v) => acc.concat(Object.values(v)), [] );
const sum = totalAttendance.reduce( (acc, v) => acc + v, 0 );
const attendance = sum / totalAttendance.length * 100;
console.log( `sum of value 1: ${sum}\nattendance percentage: ${
  attendance}%` );

相关问题