如何向数组对象中添加变量?附遍历数组查找PNG文件代码
如何向数组对象中添加变量?
嘿,我来帮你搞定这个问题!你现在是想在遍历数组arr的过程中,给每个处理后的对象(或者原数组里的对象)添加新变量对吧?结合你现有的代码,我给你两种实用的实现方式:
方式1:给返回的新对象添加变量
你的原代码通过map生成了包含Logopath属性的新对象数组,要是想给这些新对象加额外变量,直接在返回的对象里新增键值对就好。比如可以添加原对象的国家名称、图片是否存在的标记,甚至动态生成的提示信息:
const fs = require('fs'); const path = require('path'); const imageDir = '/var/scraper/public/images/flags/'; var filesExist = arr.map((imgObj) => { const imgfile = imgObj.country; let filePath = path.join(imageDir, imgfile + ".png"); const isImageFound = fs.existsSync(filePath); // 补全你原代码里的默认图片路径(这里假设是noimage.png) const fullPath = isImageFound ? filePath : path.join(imageDir, "noimage.png"); // 在返回对象中添加任意你需要的变量 return { Logopath: fullPath, // 从原对象提取属性添加 CountryName: imgObj.country, // 自定义布尔值变量 IsImageAvailable: isImageFound, // 动态生成的文本变量 StatusMessage: isImageFound ? "已找到对应国旗图片" : "使用默认占位图片" }; });
方式2:修改原数组中的对象
如果你不想生成新对象,而是直接给原数组arr里的每个imgObj添加属性,也可以在map中直接修改原对象后返回(或者用forEach遍历修改,效果类似):
const fs = require('fs'); const path = require('path'); const imageDir = '/var/scraper/public/images/flags/'; // 修改原数组对象并返回更新后的数组 var updatedArr = arr.map((imgObj) => { const imgfile = imgObj.country; let filePath = path.join(imageDir, imgfile + ".png"); const fullPath = fs.existsSync(filePath) ? filePath : path.join(imageDir, "noimage.png"); // 直接给原对象添加新属性 imgObj.Logopath = fullPath; imgObj.IsImageAvailable = fs.existsSync(filePath); // 返回修改后的原对象 return imgObj; });
额外小技巧:添加基于逻辑计算的变量
要是你需要的变量需要通过额外逻辑计算(比如文件大小),可以先在遍历过程中计算好,再添加到对象里:
var filesExist = arr.map((imgObj) => { const imgfile = imgObj.country; let filePath = path.join(imageDir, imgfile + ".png"); const isFound = fs.existsSync(filePath); const fullPath = isFound ? filePath : path.join(imageDir, "noimage.png"); // 计算文件大小(仅当文件存在时) let fileSizeBytes = null; if (isFound) { const fileStats = fs.statSync(filePath); fileSizeBytes = fileStats.size; } return { Logopath: fullPath, Country: imgObj.country, IsAvailable: isFound, // 添加计算后的变量 FileSizeBytes: fileSizeBytes }; });
内容的提问来源于stack exchange,提问作者Frederik 84
相关产品推荐
相关产品推荐

