英文:
calculating total values from a JSON data in jsreport using JavaScript
问题
我是jsreport的新手。我有以下数据,尝试计算总薪水,
{
"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
}
}]
}
我尝试使用以下代码,但一直出现错误,提示company.forEach不是一个函数。
function total(company) {
var sum = 0
company.forEach(function (i) {
sum += i.salary
})
return sum
}
我得到以下错误。
英文:
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
答案1
得分: 0
这是一个使用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)
有关详细信息,请查看数组的reduce
方法,但每当你需要在一个项目列表上进行“计算”时,reduce
都是一个不错的选择,可以用来尝试解决问题。
英文:
This is a good time to use reduce:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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)
<!-- end snippet -->
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论