简体   繁体   English

如何修改对象数组中的项目

[英]How to modify items in an array of objects

I have an array of objects as我有一个对象数组

const items = [
  {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'},
  {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'},
  {name: 'Alf', amount: '34hjbjbsdf94334', role: 'user'},

The amount in the array are encrypted.数组中的金额是加密的。 And i have a function decryptAmount() that receives amount and returns the decrypted value decryptAmount(amount)我有一个 function decryptAmount()接收金额并返回解密值decryptAmount(amount)

In the end, I want a new array as最后,我想要一个新数组

const items = [
  {name: 'Sam', amount: 101, role: 'admin'},
  {name: 'Jane', amount: 50, role: 'user'},
  {name: 'Alf', amount: 100, role: 'user'},
]

How do get my intended solution?如何获得我想要的解决方案?

Your best bet is to use the array map method.您最好的选择是使用数组map方法。 This method iterates over each array element and replaces it with the returned value.此方法迭代每个数组元素并将其替换为返回值。

let items = [...];
items = items.map(item => ({
   ...item,
   amount: decryptAmount(item.amount)
}));

Array Map on MDN : MDN 上的数组 Map

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的 function 的结果。

You can run forEach loop您可以运行 forEach 循环

items.forEach(item => {
  item.amount = decryptAmount(item.amount);
});

This will modify every amount in the array这将修改数组中的每个数量

You can try to iterate through your array and modify your objects So, you will have:您可以尝试遍历您的数组并修改您的对象因此,您将拥有:

const items = [
  {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'},
  {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'},
  {name: 'Alf', amount: '34hjbjbsdf94334', role: 'user'}]

for(let i=0; i<items.length; i++){
    items[i].amount = decryptAmount(items[i].amount);
}

That should edit the amount property of objects to the decrypted value那应该将对象的数量属性编辑为解密值

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM