如何使用JavaScript访问嵌套JSON对象并渲染到HTML?
解决访问嵌套JSON数组的错误及渲染HTML的方法
错误原因与修复
你遇到的TypeError: comments.replies is undefined,核心问题是**data.comments是数组类型**,而非单个对象——数组本身没有replies属性,replies是数组内每个comment对象的专属属性。
正确访问方式
- 访问单个评论的回复:通过数组索引定位具体评论,再调用
replies// 第一个评论的回复数组(空数组) console.log(data.comments[0].replies); // 第二个评论的回复数组 console.log(data.comments[1].replies); - 遍历所有评论的回复:用
forEach循环遍历数组中的每个评论对象data.comments.forEach(comment => { console.log(`评论ID ${comment.id} 的回复:`, comment.replies); });
渲染到HTML的实现
假设页面已有一个用于承载内容的容器:
<div id="comments-container"></div>
修改你的JavaScript代码,实现评论与回复的渲染:
fetch('./data.json', { method: 'GET', headers: { 'Accept': 'application/json', }, }) .then((response) => response.json()) .then((data) => { const container = document.getElementById('comments-container'); // 遍历每个评论 data.comments.forEach(comment => { // 创建单个评论容器 const commentEl = document.createElement('div'); commentEl.className = 'comment'; commentEl.innerHTML = ` <div class="comment-header"> <img src="${comment.user.image.png}" alt="${comment.user.username}"> <span class="username">${comment.user.username}</span> <span class="date">${comment.createdAt}</span> <span class="score">${comment.score}</span> </div> <p class="comment-content">${comment.content}</p> `; // 若当前评论有回复,渲染回复区域 if (comment.replies.length > 0) { const repliesWrap = document.createElement('div'); repliesWrap.className = 'replies'; comment.replies.forEach(reply => { const replyEl = document.createElement('div'); replyEl.className = 'reply'; replyEl.innerHTML = ` <div class="reply-header"> <img src="${reply.user.image.png}" alt="${reply.user.username}"> <span class="username">${reply.user.username}</span> <span class="replying-to">@${reply.replyingTo}</span> <span class="date">${reply.createdAt}</span> <span class="score">${reply.score}</span> </div> <p class="reply-content">${reply.content}</p> `; repliesWrap.appendChild(replyEl); }); commentEl.appendChild(repliesWrap); } container.appendChild(commentEl); }); }) .catch((error) => { console.log(error); });
可选样式补充
添加基础CSS让排版更清晰:
.comment { border: 1px solid #eee; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; } .comment-header { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; } .comment-header img { width: 40px; height: 40px; border-radius: 50%; } .username { font-weight: bold; } .date { color: #666; margin-left: auto; } .score { background: #f0f0f0; padding: 0.25rem 0.5rem; border-radius: 4px; margin-left: 0.5rem; } .replies { margin-top: 1rem; padding-left: 2rem; border-left: 2px solid #eee; } .reply { margin-bottom: 1rem; } .replying-to { color: #5357b6; font-weight: bold; }
内容的提问来源于stack exchange,提问作者CodeLover
相关产品推荐
相关产品推荐

