Search code examples
javascriptnode.jsjsonmongodbmongoose

JSON data to calculate the total attendance in percentage?


I have this attendance data for a particular student. If he was present then marked 1 else marked 0 in the respected subject. How I can calculate the total attendance out of it. Please help me out...

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

I need that I can count all those key-value pair which has a value equals 1 and then divide it by total no. of key-value pairs exist which I am finding by:

        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;

and then multipy the resultant with 100 to get the total attendance in percentage, but I don't know how to fetch only those key-value pairs count which has value as 1. Please help me.


Solution

  • You can do it with an combination of Object.entries, Object.values and .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)