我想在匹配id值后推送一个值。
我有评论JSON,它具有属性:reply
[{
"id": "1",
"root_id": "1",
"target_id": "12",
"text": "Hello World!",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago",
"reply": [{
"id": "123",
"root_id": "1",
"target_id": "222",
"text": "Nice!"
},
{
"id": "124",
"root_id": "1",
"target_id": "222",
"text": "Good!"
}
]
},
{
"id": "2",
"root_id": "2",
"target_id": "12",
"text": "Hello RG!",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago",
"reply": [{
"id": "123",
"root_id": "1",
"target_id": "222",
"text": "Hey john how are you?"
},
{
"id": "124",
"root_id": "1",
"target_id": "222",
"text": "Hi john!"
}
]
}, {
"id": "3",
"root_id": "3",
"target_id": "12",
"text": "Thanks.",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago"
}, {
"id": "4",
"root_id": "4",
"target_id": "12",
"text": "Great.",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago"
},
{
"id": "5",
"root_id": "5",
"target_id": "12",
"text": "Welcome.",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago"
}
]
评论及其回复 我想通过使用以下HTML代码来回复:
HTML
<div [attr.commentId]="commentData.id" class="addReplyContainer replyTextAreaContainer" style="display: none" >
<textarea (keyup.enter)="addReply($event,commenData.root_id)" [(ngModel)]="reply" style="width:100%" class="replyText commentText addReplyTextarea form-control"></textarea>
</div>
并希望将新制作的回复json推送到上面提到的数组中:
var reply =
{
"id": "125",
"root_id":1,
"target_id":"222",
"text":"Great!"
}
有没有办法用$ .each做到这一点?
我正在尝试下面的方法,但它给了我错误:
addReply(event, root_id)
{
let commentDataa = this.commentsData;
let replyy = this.reply;
jQuery.each(this.commentsData, function (index, value) {
if(value.root_id == root_id)
{
commentDataa.reply.push({
root_id:root_id,
target_id: "12",
text: replyy,
});
}
})
}
错误:ERROR TypeError:无法读取属性&#39; push&#39;未定义的
任何指导都将不胜感激。 先谢谢你。
答案 0 :(得分:1)
您需要访问index
数组的commentDataa
,以便您可以在commentDataa[index]
对象的特定对象中推送回复。
addReply(event, root_id);
{
let commentDataa = this.commentsData;
let replyy = this.reply;
jQuery.each(this.commentsData, function (index, value) {
if (value.root_id == root_id) {
commentDataa[index].reply.push({
root_id: root_id,
target_id: '12',
text: replyy
});
}
});
}