Home > Blockchain >  How create a new array from the fields of the objects object and the array
How create a new array from the fields of the objects object and the array

Time:01-29

I have an array and an object object, I want to formulate a new array that will contain specialization from the team array and salary from the salaries object

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);

When comparing, if the profession is not in the salary object, then the profession is renamed to the last one that is in the salary object. How to make it so that if there is no identical profession, then it is not added to the new array?.

CodePudding user response:

In your solution, when the if condition is never matched, name and workerSalary are not updated but still added into the array.

I think this would work, too (build the output objects from salaries and then add them as many times as they are matched by team members):

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)

  • Related