【问题标题】:How to remove an element from a separate JSON file using just that elements ID?如何仅使用该元素 ID 从单独的 JSON 文件中删除元素?
【发布时间】:2021-10-20 17:41:42
【问题描述】:

所以我是 JS 新手,我在网上找到的解决方案都没有对我有用。我正在为 todolist 创建一个后端,并且我想添加 app.delete 功能,以便我可以从列表中删除项目。

这是我单独的 json 文件中的代码:

    [{"id":1,"name":"item 1","complete":true},{"id":2,"name":"Walk the dog","complete":false},{"id":3,"name":"Go shopping","complete":false}]

这是我尝试过的,但老实说,我只是写了我想到的任何东西:

    app.delete('/todo/:id/delete', (request, response) => {
    const id = request.params.id

    const findTodobyID = (todos, id) => {
        for(let i = 0; i < todos.length; i++){
            if(todos[i].id === parseInt(id)){
                return i 
            }
        }
        return -1
    }  
    fs.readFile('./store/todos.json', 'utf-8', (err, data) => {
        if(err) {
            return response.status(500).send('Sorry, something went wrong.')
        }

        let todos = JSON.parse(data)
        const todoIndex = findTodobyID(todos, id)

        if (todoIndex === -1) {
            return response.status(404).send('Sorry, ID not found')
        }

        todos[todoIndex].complete = true

        fs.writeFile('./store/todos.json', JSON.delete(todos), () => {
            return response.json({'status': 'Deleted ID' + id})
        })
    })
})

这是我在 Postman 中运行时遇到的错误:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot DELETE /todos/3/delete</pre>
</body>

</html>

【问题讨论】:

  • 仅供参考,有一个内置方法 Array.prototype.findIndex 可以完成您的 findTodobyID 函数的工作。
  • 如果您要删除它,那么设置 complete 属性是没有意义的。

标签: javascript node.js json express postman


【解决方案1】:

如果你想从数组中删除todoIndexth 元素:

todos.splice(todoIndex, 1);

在写之前,你应该使用:

JSON.stringify(todos);

而不是JSON.delete(todos)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-11
    • 2020-09-18
    • 2023-01-03
    • 2021-03-15
    • 2019-03-15
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多