[英]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. 循环运行时,总是将api中的最后一个对象详细信息输入到数组中。
Here; 这里; the screenshot: https://i.imgur.com/8uqOIaZ.png
屏幕截图: 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;
}
}
}
};
Please help where am I doing it wrong? 请帮助我在哪里做错了?
Objects in JavaScript are sent via a link to the piece of memory. JavaScript中的对象通过链接发送到内存。 So when you change your
post
you are changing all the posts because all of them are looking to the same piece of memory. 因此,当您更改
post
您将更改所有帖子,因为它们都在寻找相同的内存。
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. 但是,有多种方法可以给猫咪剥皮,因此这不是唯一的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.