Home > Back-end >  Updating Json Value with that of another Json
Updating Json Value with that of another Json

Time:06-30

I want to update automatically the value of comments_list with the values in the comments JSON object

const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]})
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"})

The final output should look like this

{"tweet_id":1,"created_at":"2022-06-28","comments_list":[{"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"}]}

CodePudding user response:

I'd work with those strings in an object form, otherwise string-manipulation could be slow in some cases.

This is by no means the fastest solution but perhaps the idea behind it can be helpful.

const tweet = [{
  "tweet_id": 1,
  "created_at": "2022-06-28",
  "comments_list": []
}]; // There could be many tweet objects so wrap it in an array
const comments = [{
    "tweet_id": 1,
    "commenter_id": 2,
    "commenter_first_name": "tito",
    "commenter_username": "tito_lulu"
  },
  {
    "tweet_id": 1,
    "commenter_id": 5,
    "commenter_first_name": "me-too",
    "commenter_username": "me294"
  }
]; // Same here, could be many comments right?
let UpdatedTweets = [];
// There are faster ways to do this, but for your question
tweet.forEach((tweet, tweetIndex) => {
  // Loop each tweet
  let post = tweet;
  comments.forEach((comment, commentIndex) => {
    if (comment.tweet_id == tweet.tweet_id) {
      // we have a match lets combine them
      tweet.comments_list.push({
        commenter_id: comment.comment_id,
        commenter_first_name: comment.commenter_first_name,
        commenter_username: comment.commenter_username
      });
    }
  });
  UpdatedTweets.push(post);
});
console.log(JSON.stringify(UpdatedTweets));

CodePudding user response:

The general idea is:

  1. Parse the JSON into JS objects
  2. Update the target object with the complementary information
  3. Stringify the target object into JSON (only if you need to, eg. send the data to some other machine)

In your case:

const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]});
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2, 
"commenter_first_name":"tito","commenter_username":"tito_lulu"});

let o_tweet = JSON.parse(tweet)
  , o_comments = JSON.parse(comments)
  ;

if (Array.isArray(comments)) { // Test whether that is a single or multiple comments
    comments.forEach( c => { o_tweet.comments_list.push(c); });
} else {
    o_tweet.comments_list.push(o_comments);
}

console.log(o_tweet);

// Only if needed:
// let newtweet = JSON.stringify(o_tweet)

  • Related