如何使用for循环处理嵌套数组替代map,为用户物品添加!后缀
使用for循环实现需求的方案
实现逻辑和map方法一致,不会修改原始数组和数据,避免污染原数据
实现步骤:
- 先创建空数组存储处理后的所有用户信息
- 外层for循环遍历原数组的每个用户对象
- 对每个用户先做属性拷贝,再嵌套内层for循环遍历用户的items数组,给每个元素末尾拼接「!」生成新的items数组
- 把处理完成的用户对象推入新数组即可
完整代码如下:
const array = [ { username: "john", team: "red", score: 5, items: ["ball", "book", "pen"] }, { username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"] }, { username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"] }, { username: "tyson", team: "green", score: 1, items: ["book", "pen"] }, ]; // 存储结果的新数组 const newUserList = []; // 外层遍历所有用户 for (let i = 0; i < array.length; i++) { const currentUser = array[i]; // 拷贝原用户属性,避免修改原始数据 const processedUser = {...currentUser}; const processedItems = []; // 内层遍历items数组添加! for (let j = 0; j < currentUser.items.length; j++) { processedItems.push(currentUser.items[j] + '!'); } processedUser.items = processedItems; newUserList.push(processedUser); } // 输出验证结果 console.log(newUserList);
如果你的业务场景不需要保留原始数组数据,可以直接修改原数组的对应属性,省略拷贝步骤,代码会更精简。
内容的提问来源于stack exchange,提问作者Joel Gudasalmani
相关产品推荐
相关产品推荐

