javascript 如何从objects对象的字段和数组创建新数组

jxct1oxe  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(118)

我有一个数组和一个object对象,我想用公式表示一个新数组,其中包含来自team数组的specialization和来自salaries对象的salary

const salaries = {
TeamLead: { salary: 1000, tax: "99%" },
Architect: { salary: 9000, tax: "34%" },
Design: { salary: 3000, tax: "34%" },
}
const team = [
{ name: "Alexander", specialization: "TeamLead" },
{ name: "Gaudi", specialization: "Architect" },
{ name: "Koolhas", specialization: "Architect" },
{ name: "Foster", specialization: "Architect" },
{ name: "Inna", specialization: "Design" },
{ name: "John", specialization: "Design" },
{ name: "Anna", specialization: "BackEnd" },]

  let proffesionSalaries = Object.keys(salaries);
  let teamProffesion = team.map((worker) => worker.specialization);
  let arrProfesionSallary = [];
  let arrSalaries = Object.values(salaries);
  let salariesWithTax = arrSalaries.map((sallary) => sallary.salary + (sallary.salary * (parseInt(sallary.tax)) / 100));
  for (let i = 0; i < teamProffesion.length; i++) {
    for (let j = 0; j < proffesionSalaries.length; j++) {
      if ( teamProffesion[i] == proffesionSalaries[j]) {
         name = teamProffesion[i];
         workerSalary = salariesWithTax[j];
        }}
  arrProfesionSallary.push({profession:name,sallary:workerSalary})
  };
 console.log(arrProfesionSallary);

比较时,如果该职业不在薪资对象中,则将该职业重命名为薪资对象中的最后一个职业,如何使其在没有相同职业的情况下不添加到新数组中?

zpgglvta

zpgglvta1#

在您的解决方案中,当if条件永远不匹配时,nameworkerSalary不会更新,但仍会添加到数组中。
我认为这也可行(从salaries构建输出对象,然后根据团队成员匹配的次数添加它们):

const salaries = {
    TeamLead: { salary: 1000, tax: "99%" },
    Architect: { salary: 9000, tax: "34%" },
    Design: { salary: 3000, tax: "34%" },
    }
const team = [
    { name: "Alexander", specialization: "TeamLead" },
    { name: "Gaudi", specialization: "Architect" },
    { name: "Koolhas", specialization: "Architect" },
    { name: "Foster", specialization: "Architect" },
    { name: "Inna", specialization: "Design" },
    { name: "John", specialization: "Design" },
    { name: "Anna", specialization: "BackEnd" },
]

const calculateTotalSalary = ({salary, tax}) => salary + (salary * parseInt(tax) / 100)
const totalSalaries = Object.keys(salaries)
  .map(profession => ({profession, salary: calculateTotalSalary(salaries[profession])}))
  .reduce((total, salary) => total.concat(team.filter(t => salary.profession === t.specialization).map(_ => ({...salary}))), [])

console.log(totalSalaries)

相关问题