Saumay Paul
Saumay Paul

Reputation: 425

How to change value of Object inside an Array?

I want to change the values of the objects inside an array. I have created an object which I insert in every loop in an array.

If encountered with a missing value, I want to update the values of the existing object.

When the loop runs, it always enters the last object details from the api into the array.

Here; the screenshot: https://i.sstatic.net/n49Qc.png

var msg = data.message; // messages array from api
let body;
let posts = [];// empty array created

//object structure
let post ={
    id:'',
    desc: '',
    creator: '',
    time: '',
    likes: 0,
    attachment: '',
};
for(let i in msg){
    if(msg[i].body.includes(':')){ //if message body include object notation ':'
      body = JSON.parse(msg[i].body); // parse text message body into json
      if(body.contentDescription){ //if content is true
        post.id = body.postId; //id
        post.creator = body.createdUserName; //post creator
        post.time = body.publishedDate; //post publish date
        post.desc = body.contentDescription; //post content

        posts.push(post);
      }
      else if(posts.length > 1){
        for(let j in posts){
          if(posts[j].id === body.postId){
            console.log(posts[j].id);
            if(body.likeCount){ //if likeCount is true
              posts[j].likes += 1; //increase like count
            }else if(body.attachmentId){ //of Attachment is true
              posts[j].attachment = body.attachmentId; // update    attachement value
            }
          }
          break;
        }
      }


    }


};

Please help where am I doing it wrong?

Upvotes: 0

Views: 141

Answers (1)

Sergey Mell
Sergey Mell

Reputation: 8040

Objects in JavaScript are sent via a link to the piece of memory. So when you change your post you are changing all the posts because all of them are looking to the same piece of memory.

You can change your code in a next way so it start working correct

...
if(body.contentDescription){ //if content is true
    let postItem = Object.assign({}, post); // Coping an object so breaking the memory link
    postItem.id = body.postId; //id
    postItem.creator = body.createdUserName; //post creator
    postItem.time = body.publishedDate; //post publish date
    postItem.desc = body.contentDescription; //post content

    posts.push(postItem);
  }
...

However, there is more than one way to skin a cat so this is not the only solution.

Upvotes: 1

Related Questions