![](/img/trans.png)
[英]How can i remove an object from array of objects in app.delete using express
[英]How do I use express.js app.delete to remove a specific object from an array?
我正在使用 node 和 express 来设置服务器并执行获取、发布、删除等操作。但我无法弄清楚按 id 删除的方法。 我知道如何获取特定的 id,但我不知道最后一部分。
这是我到目前为止所拥有的。 这正确地返回了 obj.id。
app.delete("/api/notes/:id", function(req, res) {
console.log("req params", req.params.id)
});
假设您的数组只是一个标准数组,从数组中删除项目的最简单方法是使用.filter()
返回该数组的新副本,而不包含您要删除的项目。
app.delete("/api/notes/:id", function(req, res) {
console.log("req params", req.params.id)
myArray = myArray.filter(({ id }) => id !== req.params.id);
});
否则,如果您需要改变(修改)现有数组,则可以使用.findIndex()
和.splice()
代替。
app.delete("/api/notes/:id", function(req, res) {
console.log("req params", req.params.id)
const itemIndex = myArray.findIndex(({ id }) => id === req.params.id);
if (itemIndex >= 0) {
myArray.splice(itemIndex, 1);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.