Home > Mobile >  How do I add new field to the object in JavaScript while copying it from another existing one?
How do I add new field to the object in JavaScript while copying it from another existing one?

Time:04-15

supposed I query something & got a data object from db

"_id": "3ir23oir2",
"content" : "This a comment String!",
"liked_by_users" : ["234234ff3","23432fdg","234f34r23", "232342f34r233"],
"timestamp": "2022-04-15T16:08:24.336Z",
"post_id": "er234fef34",
"commenter", "23rv34r3r"
 }

but I want want to send it with two more addional field i.e. is_liked_by_me of type boolean & like_counts of type number

"_id": "3ir23oir2",
"content" : "This a comment String!",
"liked_by_users" : ["234234ff3","23432fdg","234f34r23", "232342f34r233"],
"timestamp": "2022-04-15T16:08:24.336Z",
"post_id": "er234fef34",
"commenter", "23rv34r3r",
"is_liked_by_me": false,
"total_likes"  : 4
 }

just suggest to me an easy way of copying these object, I'm just feeling a little lazy to write or map them...

CodePudding user response:

Say your response is:

let response = {
  "_id": "3ir23oir2",
  "content" : "This a comment String!",
  "liked_by_users" : ["234234ff3","23432fdg","234f34r23", "232342f34r233"],
  "timestamp": "2022-04-15T16:08:24.336Z",
  "post_id": "er234fef34",
  "commenter", "23rv34r3r"
 }

to add new field simply access it like you would an array but with a string as the accessor. That is:

response['is_liked_by_me'] = false;
response['total_likes'] = 4;

And if you want your initial object to stay intact you can do a shallow copy by desctructuring the object and then make changes on it:

let responseCopy = {...response};
responseCopy['is_liked_by_me'] = false;
responseCopy['total_likes'] = 4;

JavaScript ES6 Destructuring Docs

CodePudding user response:

Frist of all your json code snippet is wrong.

I believe that the following is right json code snippet.

  const origin = {
    _id: "3ir23oir2",
    content: "This a comment String!",
    liked_by_users: ["234234ff3", "23432fdg", "234f34r23", "232342f34r233"],
    timestamp: "2022-04-15T16:08:24.336Z",
    post_id: "er234fef34",
    commenter: "23rv34r3r",
  };
  const updated = {
    _id: "3ir23oir2",
    content: "This a comment String!",
    liked_by_users: ["234234ff3", "23432fdg", "234f34r23", "232342f34r233"],
    timestamp: "2022-04-15T16:08:24.336Z",
    post_id: "er234fef34",
    commenter: "23rv34r3r",
    is_liked_by_me: false,
    total_likes: 4,
  };

you can get updated json from the origin like the following

const updatedJson = {
...origin,
 is_liked_by_me: false,
 total_likes: 4,
} 
  • Related