简体   繁体   English

如何更新数组中对象的所有值?

[英]How do i update all values of an object in an array?

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?当每个薪水都是对象的属性并且每个对象都存储在数组中时,如何更改所有薪水值并将它们增加一个百分比? Eg increasing by 10 percent and I have to round the result up to the nearest integer:例如增加 10%,我必须将结果四舍五入到最接近的整数:

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

The map method should do what you want. map 方法应该做你想做的事。 Note the destructuring of salaryObj to avoid manipulating the original object.注意salaryObj的解构以避免操纵原始对象。

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

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.评论添加到上面的片段。

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 raise then instead of multiplying by the raise , in this case 10 , multiply by 100+raise由于您的目标是通过raise then 来提高薪水,而不是乘以raise ,在这种情况下10 ,乘以100+raise
  • You do not have to hard-code raise since you're passing it to the function;您不必对raise进行硬编码,因为您将它传递给函数; it allows you to pass 5 , or 15 or some other raise value without changing your function.它允许您在不更改功能的情况下传递515或其他一些提升值。

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

Here's a simple approach with map and Object spreading:这是一种使用map和对象传播的简单方法:

 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.对于每个元素,我们解构输入以从对象的其余部分中提取salary ,然后创建一个包含其余部分的新结果,但工资是根据原始工资和百分比调整计算得出的。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查对象属性是否包含指定数组中的所有值? - How do I check if an object property contains all values from a specified array? 如何从我的Json对象获取所有ID,名称值和位置到数组中 - How do I get All ID, Name values and location into array from my Json Object 如何在对象内的数组中更新数组? - How do I update an an array, within an object, within an array? 如何将对象属性值与数组值进行比较,然后将对象值替换为数组值? - How do I compare an object property values to the values of an array, and then replace the object values with the array values? 如何从一个数组和一个对象中.map()一个新的值数组? - How do I .map() a new array of values from an array and an object? 如何使用数组中的值更新文本框值? - How do I update a textbox value using values from an array? 我如何使用 setState 更新数组内的对象 - How do i use setState to update an object inside an array 我如何在 React 的数组中更新 object 中的键值? - How do i update value of a key in an object inside an Array in React? 如何更新作为数组的 JavaScript class object? - How do I update a JavaScript class object that is an array? 如何在Typescript中更新数组列表的对象? - How do I update the object of an array list in Typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM