简体   繁体   English

通过 id nodejs, javascript 删除数组中的 object

[英]Delete an object in array by id nodejs , javascript

I am having issues deleting an object by id in an array(database).我在通过数组(数据库)中的 id 删除 object 时遇到问题。

route.delete('/:id', (req, res) =>{
let match = false
for(let i=0; i< database.posts.length; i++){
if(id == database.posts[i].id){
match = true;
database.posts.splice(id, 1)
}
return res.json({status: 'Success', message : 'Entry deleted'}
}
}
if(!match){
return res.json('Cannot delete entry')
}
} )

`````

In my database I have a list of object with its unique id (1- 10), meaning the index is (0-9).在我的数据库中,我有一个 object 列表,其唯一 ID (1-10),表示索引为 (0-9)。 The code work fine when I start deleting by id fromthe end of the array.当我从数组末尾开始按 id 删除时,代码工作正常。 But when I delete from the middle of the array,it delete another posts instead.但是当我从数组中间删除时,它会删除另一个帖子。 For example, if I delete an object with id 3 (index 2), afterward trying deleting an object with id 4, the code deletes object with id 5 instead because there's been a change in the index.例如,如果我删除一个 ID 为 3(索引 2)的 object,然后尝试删除一个 ID 为 4 的 object,代码将删除 object,因为索引为 5 发生了变化。

Please can I better improve this code to work appropriate?
route.delete('/:id', (req, res) => {
    let match = database.posts.findIndex(post => post.id === req.params.id)
    if (match < 0) // not found returns -1
        return res.status(404).json({ status: 'error', message: 'Entry ID not found' })
    
    database.posts.splice(match, 1)
    return res.json({ status: 'success', message: 'Entry deleted' })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM