[英]JS - Render all comments
I have json data that looks like this:我有如下所示的 json 数据:
{
"comment_ds": [
{
"c_user": [
"Bob",
"Bob",
"Bob",
"Bob",
"Bob"
],
"c_user_img": [
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg",
"/media/accounts/1809094310/1809094310.jpg"
],
"c_content": [
"nice",
"awesome",
"very cool",
"great",
"perfect"
]
}
]
}
I am using this part of an ajax response to render the data:我正在使用 ajax 响应的这一部分来呈现数据:
success: function(data) {
comm_data = data['comment_ds'][0];
var i = 0;
Object.entries(comm_data).forEach(([key, value]) => {
if (i < value.length){
c_user = comm_data["c_user"][i];
c_content = comm_data["c_content"][i];
c_user_img = comm_data["c_user_img"][i];
comment = document.createElement('tr');
comment.setAttribute('class','comment')
$(comment).html(`
<th class="comm_th_1"><img class="comm_user_image" src="${c_user_img}"><a class="comm_user">${c_user}</a></th>
<th class="comm_th_2">${c_content}</th>
<th class="comm_th_3"></th>`);
$('.comm_cont').append(comment);
}
i+=1;
});
}
}
It works for the first 3 comments but then stops.它适用于前 3 条评论,但随后停止。
When I console.log value.length
, I get 5, but i
stops incrementing at 3.当我 console.log value.length
,我得到 5,但i
停止增加 3。
Thank you for any suggestions谢谢你的任何建议
You can make a loop via c_user
property using forEach
method.您可以使用forEach
方法通过c_user
属性进行循环。 This method supports for indexer.此方法支持索引器。
Since c_user
, c_user_img
and c_content
have the same size, you can use that index in order to assign another values: c_user_img
c_content
:由于c_user
、 c_user_img
和c_content
具有相同的大小,您可以使用该索引来分配另一个值: c_user_img
c_content
:
var data = { "comment_ds": [ { "c_user": [ "Bob", "Bob", "Bob", "Bob", "Bob" ], "c_user_img": [ "/media/accounts/1809094310/1809094310.jpg", "/media/accounts/1809094310/1809094310.jpg", "/media/accounts/1809094310/1809094310.jpg", "/media/accounts/1809094310/1809094310.jpg", "/media/accounts/1809094310/1809094310.jpg" ], "c_content": [ "nice", "awesome", "very cool", "great", "perfect" ] } ] }; comm_arr = data['comment_ds']; comm_data = comm_arr[0]; comm_data.c_user.forEach(function (user, index) { img = comm_data.c_user_img[index]; content = comm_data.c_content[index]; console.log(user, img, content); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.