[英]How to modify items in an array of objects
我有一个对象数组
const items = [
{name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'},
{name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'},
{name: 'Alf', amount: '34hjbjbsdf94334', role: 'user'},
数组中的金额是加密的。 我有一个 function decryptAmount()
接收金额并返回解密值decryptAmount(amount)
最后,我想要一个新数组
const items = [
{name: 'Sam', amount: 101, role: 'admin'},
{name: 'Jane', amount: 50, role: 'user'},
{name: 'Alf', amount: 100, role: 'user'},
]
如何获得我想要的解决方案?
您最好的选择是使用数组map
方法。 此方法迭代每个数组元素并将其替换为返回值。
let items = [...];
items = items.map(item => ({
...item,
amount: decryptAmount(item.amount)
}));
map()
方法创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的 function 的结果。
您可以运行 forEach 循环
items.forEach(item => {
item.amount = decryptAmount(item.amount);
});
这将修改数组中的每个数量
您可以尝试遍历您的数组并修改您的对象因此,您将拥有:
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);
}
那应该将对象的数量属性编辑为解密值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.