You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用另一个JSON对象自动更新目标JSON的comments_list字段值

解决方法:将评论数据合并到推文的评论列表中

嘿,我来帮你搞定这个需求!你现在需要把评论数据添加到推文的comments_list数组里,不过因为原始数据都是经过JSON.stringify()处理后的字符串,得先转成可操作的JavaScript对象,处理完再转回JSON字符串。

具体步骤和代码实现:

  1. 解析JSON字符串为JS对象:先用JSON.parse()把字符串转成对象,这样才能修改属性
  2. 提取有效评论字段:从评论数据里剔除tweet_id(因为推文本身已经关联了这个ID,不需要重复存储)
  3. 添加到评论列表:把处理后的评论对象推入推文的comments_list数组
  4. 转回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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:44:08