Vue.js中forEach循环映射JSON到对象报错求助
解决提取href字段时的TypeError问题
我的函数接收pImageArray(JSON对象)作为输入,遍历该对象并从存储中读取数据得到新的JSON对象。想要提取其中的href字段生成新对象data时,出现错误:Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')。尝试两种写法仍无法解决,求思路。
尝试的代码1
getFileForView: function (pImageArray) { const storage = new Storage(client); pImageArray.forEach(function (element) { const result = storage.getFileView(bucketID, element.image_ID); console.log("--- image for view in loop : ", result.href); // Success console.log("--- image result : ", result); // Success const data = result.map(value => ({ href: value.href })); console.log("--- data : ", data); });
尝试的代码2
getFileForView: function (pImageArray) { const storage = new Storage(client); var jsonData = []; var newJSONData = []; pImageArray.forEach(function (element) { const result = storage.getFileView(bucketID, element.image_ID); console.log("--- image for view in loop : ", result.href); // Success console.log("--- image result : ", JSON.stringify(result)); // Success jsonData["href"] = result.href; newJSONData.push(jsonData); console.log("--- data : ", newJSONData); });
问题分析
- 代码1的直接错误:
result是单个文件数据对象,不是数组,而map()是数组的专属方法,直接调用会触发类型错误。你看到console打印出result.href正常,说明result本身是带href属性的单个对象,根本不需要用map处理。 - 隐藏的异步问题:
storage.getFileView是异步操作,返回的是Promise对象。你当前同步写法里,result其实是Promise而非实际的文件数据——浏览器console能显示href是因为Promise后续resolve后,浏览器异步更新了日志展示,但同步代码里处理会导致数据不稳定。
修正方案
改用异步函数+Promise.all处理批量异步操作,同时直接提取单个对象的href:
getFileForView: async function (pImageArray) { const storage = new Storage(client); // 用map遍历数组,同时处理每个异步请求 const newJSONData = await Promise.all(pImageArray.map(async (element) => { // 等待异步请求完成,拿到真实的结果对象 const result = await storage.getFileView(bucketID, element.image_ID); // 直接返回包含href的新对象 return { href: result.href }; })); console.log("--- final data : ", newJSONData); return newJSONData; }
代码2的问题说明
代码2里把jsonData定义成数组,却用jsonData["href"]给数组添加属性,这是错误用法——应该把jsonData定义成普通对象var jsonData = {};。另外同样没处理异步问题,会导致result.href可能取不到正确值。
内容的提问来源于stack exchange,提问作者Ralf Bordé
相关产品推荐
相关产品推荐

