JavaScript遍历JSON文件提取comments数组text属性的实现方法
问题排查&修正方案
原代码错误点
- 变量命名混淆:
JSON.parse返回的是整个JSON根对象,你将其命名为comments,但实际存储评论数组的是根对象下的comments属性,二者完全不是一个东西 for...in遍历对象拿到的是键名而非值:第一层循环里的i是字符串类型的键"comments",不是评论数组- 第二层遍历直接遍历字符串
i,拿到的j是字符串的字符索引,不可能取到text属性
正确实现代码
const fs = require('fs') const path = require('path') // 读取&解析JSON逻辑可以保留 const data = fs.readFileSync(path.resolve(__dirname, 'comments.json')); const jsonResult = JSON.parse(data); // 先拿到评论数组 const commentArr = jsonResult.comments; // 最简洁的遍历方式:forEach commentArr.forEach(item => { console.log(item.text) }) // 如果需要支持循环中break/continue,用for...of // for (const item of commentArr) { // console.log(item.text) // }
内容的提问来源于stack exchange,提问作者WallStreetBets
相关产品推荐
相关产品推荐

