如何保存forEach遍历的元素并通过res.send返回至Postman?
问题描述
使用forEach遍历currencies.data和timezones.default时,仅能打印el.currency和el.label到终端,但尝试将这些值保存到变量cc和tz后返回给Postman时,这两个变量始终是undefined,无法正常返回数据。
原代码如下:
let cc = currencies.data.forEach(el => console.log(el.currency)) let tz = timezones.default.forEach(el => console.log(el.label)) res.status(200).send({ status: true, status_code: 'SUCCESS', message: 'SUCCESS', currency: cc, timezones: tz, });
需求:正确保存el.currency和el.label并返回给请求端。
解决方案
问题核心是**forEach方法没有返回值(默认返回undefined)**,所以你赋值给cc和tz的其实都是undefined。要生成包含目标字段的数组,应该用map方法——它会遍历数组并返回一个由处理后元素组成的新数组。
修改后的代码如下:
// 用map生成只包含currency的数组,同时保留打印逻辑 let cc = currencies.data.map(el => { console.log(el.currency); return el.currency; }); // 用map生成只包含label的数组,同时保留打印逻辑 let tz = timezones.default.map(el => { console.log(el.label); return el.label; }); res.status(200).send({ status: true, status_code: 'SUCCESS', message: 'SUCCESS', currency: cc, timezones: tz, });
如果不需要打印终端输出,也可以简化成一行:
let cc = currencies.data.map(el => el.currency); let tz = timezones.default.map(el => el.label);
此时cc会是一个由所有el.currency组成的数组,tz是由所有el.label组成的数组,就能正常通过res.send返回给Postman了。
内容的提问来源于stack exchange,提问作者samtuner
相关产品推荐
相关产品推荐

