我想更改数组内对象的值。我创建了一个对象,将其插入到数组中的每个循环中。
如果遇到缺失值,我想更新现有对象的值。
当循环运行时,它总是将最后一个对象详细信息从 api 输入到数组中。
这里;截图:/image/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;
}
}
}
};
请帮忙看看我哪里做错了?
最佳答案
JavaScript 中的对象通过链接发送到内存块。因此,当您更改帖子
时,您正在更改所有帖子,因为所有帖子都在查找同一 block 内存。
您可以通过以下方式更改代码,使其开始正常工作
...
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);
}
...
但是,给猫剥皮的方法不止一种,因此这不是唯一的解决方案。
关于javascript - 如何更改数组中对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073486/