Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
How to delete data, using Rest api in an array stored in a JSON file, based on http request that's made by user?

I have a task that requires me to delete some data in an array that is in a JSON file, using node/express. I want, when a delete request is made, to delete a specific item that matches a specific id in the array that is in the JSON file. I tried using the filter method, but it doesn't seem to work.

JS file:

var obj = { projects: []};
app.post('/', (req, res, next)=>{
    let identifier = req.query.identify; //id of project

    fs.readFile('webProjects.json', (err, data)=>{
        if(err) throw err;
            obj = JSON.parse(data);
            obj.projects.push({id:identifier, game: req.query.project});
            let json = JSON.stringify(obj);
            fs.writeFile('webProjects.json', json, (err)=>{
                if(err) throw err
                console.log("updatedd")
            })
    })
})

/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next)=>{

    fs.readFile('webProjects.json', (err, data)=>{
        console.log(data)
        obj = JSON.parse(data);
        obj.projects.filter((item)=>{
            let url = req.query.identify; 
            return item.id !== url;
        })
        console.log(obj)
        let json = JSON.stringify(obj);
        fs.writeFile('webProjects.json', json, (err)=>{
            if(err) throw err;
            console.log(obj)
        })
    })
})

/*when user navigates to another page, we display the data of the resource*/
app.get('/:id', (req, res, next)=>{
    fs.readFile('webProjects.json', (err, data)=>{
     if (err) throw err
     res.send(data);
    })
})


/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get('*', (req, res, next)=>{
    let err = new Error('There was an error in accessing the page you wanted');
    err.statusCode = 404;
    next(err);
})

app.use((err, req, res, next)=>{
    console.log(err.message)
    if(!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
})

app.listen(8080, ()=>{
    console.log("server has listened")
})

JSON file/data:

{"projects":[{"id":"1","game":"miniGame"},{"id":"2","game":"min"}]}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The filter function does not change the array so you need to assign the filtered items back to the array.

fs.readFile('webProjects.json', (err, data)=>{
    console.log(data)
    obj = JSON.parse(data);

    // assign the filtered array back to the original array
    obj.projects = obj.projects.filter((item)=>{
        let url = req.query.identify; 
        return item.id !== url;
    })

    console.log(obj)
    let json = JSON.stringify(obj);
    fs.writeFile('webProjects.json', json, (err)=>{
        if(err) throw err;
        console.log(obj)
    })
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda