javascriptjsreport

calculating total values from a JSON data in jsreport using JavaScript


I am new to jsreport. I have the following data and trying to calculate total salaries,

{
    "company": [{
            "Remy": {
        "age": 32,
        "employer": "emp1",
        "salary": 20000
    },
    "Piet": {
        "age": 35,
        "employer": "emp2",
        "salary": 50000
    },
        "Thando": {
        "age": 32,
        "employer": "emp3",
        "salary": 20000
    },
        "Greg": {
        "age": 33,
        "employer": "emp4",
        "salary": 70000
    }
    }]
    
}

I tried using the following code but I keep getting an error that company.forEach is not a function

function total(company) {
    var sum = 0
    company.forEach(function (i) {
        sum += i.salary
    })
    return sum
}

I am getting the following error.

Report "Issue" render failed.

Error when evaluating engine handlebars for template anonymous
(because) "total" helper call failed
(because) company.forEach is not a function

(sandbox.js line 14:13)

  12 | function total(company) {
  13 |     var sum = 0
> 14 |     company.forEach(function (i) {
     |             ^
  15 |         sum += i.salary
  16 |     })
  17 |     return sum

Solution

  • This is a good time to use reduce:

    const data = {
        "company": [{
            "Remy": {
                "age": 32,
                "employer": "emp1",
                "salary": 20000
            },
            "Piet": {
                "age": 35,
                "employer": "emp2",
                "salary": 50000
            },
            "Thando": {
                "age": 32,
                "employer": "emp3",
                "salary": 20000
            },
            "Greg": {
                "age": 33,
                "employer": "emp4",
                "salary": 70000
            }
        }]    
    }
    
    const salaries = Object.values(data.company[0]).reduce((total, emp) => {
        total = emp.salary + total;
        return total;
    }, 0)
    
    console.log(salaries)

    Have a look at the array reduce method for details, but whenever you hear 'calculating' on a list of items reduce isn't a bad option to have a look at to try to solve the issue