如何更改数组内对象的值?

时间:2019-01-07 11:26:10

标签: javascript

我想更改数组内对象的值。我创建了一个对象,将其插入数组的每个循环中。

如果遇到缺少的值,我想更新现有对象的值。

循环运行时,总是将api中的最后一个对象详细信息输入到数组中。

这里;屏幕截图:https://i.imgur.com/8uqOIaZ.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;
        }
      }


    }


};

请帮助我在哪里做错了?

1 个答案:

答案 0 :(得分:1)

JavaScript中的对象通过链接发送到内存。因此,当您更改post时,您也在更改所有帖子,因为它们都在寻找相同的记忆。

您可以以另一种方式更改代码,以使其开始正确运行

...
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);
  }
...

但是,有多种方法可以给猫剥皮,所以这不是唯一的解决方法。