如何修改对象数组元素?解密amount字段生成目标数组
实现方案
你可以使用JavaScript的Array.prototype.map()方法遍历原数组,对每个对象的amount字段做解密处理,同时保留其他字段内容,最终生成目标新数组。
代码示例
// 原数组 const items = [ {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'}, {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'}, {name: 'Alf', amount: '34hjbjbsdf94334', role: 'user'}, ]; // 你已有的解密函数(直接使用你的实际函数即可) function decryptAmount(encryptedAmount) { // 这里是实际解密逻辑,示例仅模拟返回对应数值 switch(encryptedAmount) { case '455gbjsdbf394545': return 101; case 'iwhru84252nkjnsf': return 50; case '34hjbjbsdf94334': return 100; default: return 0; } } // 生成处理后的新数组 const processedItems = items.map(item => ({ ...item, // 复制原对象所有字段 amount: decryptAmount(item.amount) // 替换为解密后的数值 })); console.log(processedItems);
补充说明
map()会创建全新数组,不会修改原数组,避免意外污染原始数据。- 若你的
decryptAmount是异步函数,改用Promise.all()结合map处理:
// 假设decryptAmount为异步函数 async function decryptAmount(encryptedAmount) { // 异步解密逻辑 } async function processItems() { const processedItems = await Promise.all( items.map(async item => ({ ...item, amount: await decryptAmount(item.amount) })) ); return processedItems; } // 调用获取结果 processItems().then(result => console.log(result));
内容的提问来源于stack exchange,提问作者merlin
相关产品推荐
相关产品推荐

