Home > Back-end >  How do i update all values of an object in an array?
How do i update all values of an object in an array?

Time:06-04

How do I change all salary values and increase them by a percentage, when each salary is a property of an object, with each object being stored in an array? E.g. increasing by 10 percent and I have to round the result up to the nearest integer:

raiseSalary([
    { name: "Ali", salary: 3000 },
    { name: "Rob", salary: 2000 },
    { name: "Adam", salary: 4500 },
], 10)

The above call should return:

[
   { name: 'Ali', salary: 3300 },
   { name: 'Rob', salary: 2200 }, 
   { name: 'Adam', salary: 4950 }
]

This is the code that I have written:

function raiseSalary(arr, raise) {
    if (arr.length === 0) {
        return [{}];
    } else {
        const raiseArray = arr.map((salaryObj) => {
            return (salaryObj.salaryObj / 100) * 10;
        });
    }
}

CodePudding user response:

You're almost there. Just a few points

  • Just as you return something when the array has zero elements, you have to return something when it has elements; in this case the modified array
  • Retain the objects by using their keys and providing the data, otherwise, you end up with an array of just numbers.
  • Since your aim is to raise salary by increment the instead of multiplying by the raise, in this case 10, multiply by 100 raise
  • You do not have to hard-code raise since you're passing it to the function; it allows you to pass 5, or 15 or some other raise value without changing your function.

const input = [{ name: "Ali", salary: 3000 }, { name: "Rob", salary: 2000 }, { name: "Adam", salary: 4500 }],
      increment = 10;
      
function raiseSalary(arr, raise) {
    if (arr.length === 0) {
        return [];
    } else {
        return arr.map((salaryObj) => {
            return ({name:salaryObj.name, salary:(salaryObj.salary / 100) * (100 raise)});
        });
    }
}

console.log( raiseSalary(input, increment) );

Alternatively ...

Just return the modified array without testing for elements, and you can also use object destructuring.

const input = [{ name: "Ali", salary: 3000 }, { name: "Rob", salary: 2000 }, { name: "Adam", salary: 4500 }],
      increment = 10;
      
function raiseSalary(arr, raise) {
    return arr.map(({name,salary}) => {
        return ({name, salary: salary/100*(100 raise)});
    });
}

console.log( raiseSalary(input, increment) );
console.log( raiseSalary([], increment) );

CodePudding user response:

The map method should do what you want. Note the destructuring of salaryObj to avoid manipulating the original object.

const percent = 10;
const multiplier = 1   (percent / 100);
const salaries = [
  { name: "Ali", salary: 3000 },
  { name: "Rob", salary: 2000 },
  { name: "Adam", salary: 4500 },
];
const newSalaries = salaries.map((salaryObj) => {
  return {
    ...salaryObj,
    salary: salaryObj.salary * multiplier,
  };
});

console.log(newSalaries);

CodePudding user response:

Presented below is one possible way to achieve the desired objective.

Code Snippet

const addRaise = (arr, pcnt) => (
  arr.map(
    ({ salary, ...rest }) => ({
      ...rest,
      salary: (  salary * ( pcnt   100) / 100 )
    })
  )
);

/*
// method to raise salary by "pcnt" percent
const addRaise = (arr, pcnt) => (
  // iterate over array "arr"
  arr.map(
    // destructure to access "salary"
    ({ salary, ...rest }) => ({
      ...rest,        // all other props retained as-is
      // salary updated to be 10% more than current
      salary: (  salary * ( pcnt   100) / 100 )
    })
  )
);
*/

const dataArr = [{
    name: "Ali",
    salary: 3000
  },
  {
    name: "Rob",
    salary: 2000
  },
  {
    name: "Adam",
    salary: 4500
  },
];

console.log(
  'adding raise of 10%...\n',
  'new array:\n',
  addRaise(dataArr, 10)
);

Explanation

Comments added to the snippet above.

CodePudding user response:

Here's a simple approach with map and Object spreading:

const updateSalaries = (people, pct) => people .map (({salary, ...rest}) => ({
  ...rest,
  salary: Math .round (salary * (100   pct) / 100)
}))

const people = [{name: "Ali", salary: 3000}, {name: "Rob", salary: 2000}, {name: "Adam", salary: 4500}]

console .log (updateSalaries (people, 10))
.as-console-wrapper {max-height: 100% !important; top: 0}

For each element, we destructure the input to extract the salary from the rest of the object, and then create a new result containing the rest, but with a salary calculated from the original salary and the percentage adjustment.

CodePudding user response:

let userDetail=[
        { name: "Ali", salary: 3000 },
        { name: "Rob", salary: 2000 },
        { name: "Adam", salary: 4500 },
    ];
function getPercentage(num, percentage){
   return num * (percentage / 100);
}
userDetail=userDetail.map(x=> {
    return{
        ...x,
        salary:x.salary getPercentage(x.salary,10)
    }
        })
console.log(userDetail)
  • Related