如何使用另一个JSON对象自动更新目标JSON的comments_list字段值
解决方法:将评论数据合并到推文的评论列表中
嘿,我来帮你搞定这个需求!你现在需要把评论数据添加到推文的comments_list数组里,不过因为原始数据都是经过JSON.stringify()处理后的字符串,得先转成可操作的JavaScript对象,处理完再转回JSON字符串。
具体步骤和代码实现:
- 解析JSON字符串为JS对象:先用
JSON.parse()把字符串转成对象,这样才能修改属性 - 提取有效评论字段:从评论数据里剔除
tweet_id(因为推文本身已经关联了这个ID,不需要重复存储) - 添加到评论列表:把处理后的评论对象推入推文的
comments_list数组 - 转回JSON字符串:最后用
JSON.stringify()得到最终的目标JSON
// 你的原始JSON字符串 const tweetStr = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]}); const commentsStr = JSON.stringify({"tweet_id":1,"commenter_id": 2,"commenter_first_name":"tito","commenter_username":"tito_lulu"}); // 1. 解析为可操作的JS对象 const tweet = JSON.parse(tweetStr); const comments = JSON.parse(commentsStr); // 2. 提取评论核心数据(解构赋值剔除tweet_id) const { tweet_id: _, ...commentData } = comments; // 3. 将评论添加到推文的评论列表 tweet.comments_list.push(commentData); // 4. 转换回JSON字符串,得到你想要的结果 const finalResult = JSON.stringify(tweet); console.log(finalResult);
运行这段代码后,输出的结果就是你需要的:
{"tweet_id":1,"created_at":"2022-06-28","comments_list":[{"commenter_id":2,"commenter_first_name":"tito","commenter_username":"tito_lulu"}]}
扩展说明:
如果之后需要处理多条评论,只需要把评论数据改成数组,然后循环推入即可,比如:
// 假设是多条评论的JSON字符串数组 const commentsArrStr = JSON.stringify([ {"tweet_id":1,"commenter_id":2,"commenter_first_name":"tito","commenter_username":"tito_lulu"}, {"tweet_id":1,"commenter_id":3,"commenter_first_name":"anna","commenter_username":"anna_m"} ]); const commentsArr = JSON.parse(commentsArrStr); // 循环添加每条评论 commentsArr.forEach(comment => { const { tweet_id: _, ...commentData } = comment; tweet.comments_list.push(commentData); });
内容的提问来源于stack exchange,提问作者Tito Lulu
相关产品推荐
相关产品推荐

