我有数组,我想创建div,每个职业类型,并显示每个职业的工资总额。
但是我有问题来做这个函数,我找不到错误。
我尝试过:let totalSum = array.filter(dep => dep.profession == name).map(filt => filt.salary).reduce((acc, score) => acc + score, 0);,但问题是获取名称
代码如下:
let array = [
{name: Peter, profession: teacher, salary: 2000},
{name: Ana, profession: teacher, salary: 2000},
{name: Bob, profession: policeman, salary: 3000}]
function getDepartments(target, array) {
let keyArray = array.map(function (obj) {
for (let [key, value] of Object.entries(obj)) {
if (key === target) {
return value;
}
}
});
const createDepartments = function (array) {
let set = Array.from(new Set([...array]));
set.forEach(function (name) {
let chk = `<span>totala salary for profession ${name}:
//here I would like to put "total sum of salary" ${totalSum}
</span>`;
summary.lastElementChild.insertAdjacentHTML('beforeend', chk);
});
};
summary.insertAdjacentHTML('beforeend', `<div class="dataSummary"><span></span></fieldset>`)
createDepartments(keyArray);
}
getDepartments('profession', array);感谢您的帮助:)
发布于 2019-05-14 20:37:24
要按职业获取薪水,首先应用过滤器,然后可以从过滤后的数组中求出薪水的总和。
let input = [
{name: 'Peter', profession: 'teacher', salary: 2000},
{name: 'Ana', profession: 'teacher', salary: 2000},
{name: 'Bob', profession: 'policeman', salary: 3000}
];
function getSalaryByProfession(professionName) {
return input.filter(({profession}) => profession == professionName)
.reduce((accu, {salary}) => accu + salary , 0);
}
console.log(getSalaryByProfession('teacher'));
发布于 2019-05-14 20:52:52
let input = [
{name: 'Peter', profession: 'teacher', salary: 2000},
{name: 'Ana', profession: 'teacher', salary: 2000},
{name: 'Bob', profession: 'policeman', salary: 3000}
];
function getSalaryByProfession(professionName) {
return input.filter(({profession}) => profession == professionName)
.reduce((accu, {salary}) => accu + salary , 0);
}
let const uniqueProfession = [];
input.forEach(o => {
if(!uniqueProfession.includes(o.profession)) {
uniqueProfession.push(o.profession);
getSalaryByProfession(o.profession);
// Write logic of creating div
}
})https://stackoverflow.com/questions/56130453
复制相似问题