如何访问对象数组中评论的键?循环遍历评论实现咨询
解决遍历用户评论键与内容的问题
嘿,我来帮你搞定这个遍历评论的需求!你已经走到一半啦——现在只需要在现有循环里再加一层,用来遍历每条评论对象里的键(也就是你说的A、B、C这类)就行。
方法一:使用传统的for...in循环
这和你原来的代码风格保持一致,容易理解:
for(var key in result){ // key 是用户名:Gokul、Kavin等 const userComments = result[key].comments; for(var commentIndex in userComments){ // commentIndex 是评论的索引:0、1、2等 const commentObj = userComments[commentIndex]; // 遍历这条评论里的所有键(A、B、C) for(var commentKey in commentObj){ // 输出用户、评论键和对应的内容 console.log(`用户 ${key} 的评论键 ${commentKey}: ${commentObj[commentKey]}`); } } }
方法二:使用ES6+的现代语法(更简洁安全)
如果你的环境支持ES6,推荐用这个写法,避免var的变量提升问题,同时Object.keys()只会遍历对象自身的可枚举属性,更可靠:
// 遍历所有用户名 for(const username of Object.keys(result)){ const userComments = result[username].comments; // 遍历该用户的每一条评论 userComments.forEach((commentObj, index) => { // 拿到这条评论的所有键 Object.keys(commentObj).forEach(commentKey => { console.log(`用户 ${username} 的第${index+1}条评论,键${commentKey}: ${commentObj[commentKey]}`); }); }); }
关键说明
- 不管用哪种方法,核心都是在遍历到单条评论对象后,再遍历它的键——也就是
commentObj(比如result["Vignesh"]["comments"][0]这个对象)的所有属性键。 - 如果你想单独收集所有评论键(比如把A、B、C存到数组里),可以在遍历
commentKey的时候把它push到一个数组里,比如:const allCommentKeys = []; allCommentKeys.push(commentKey);
内容的提问来源于stack exchange,提问作者Willy Wunka
相关产品推荐
相关产品推荐

