Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
¿Cómo eliminar datos, usando Rest api en una matriz almacenada en un archivo JSON, según la solicitud http realizada por el usuario?

Tengo una tarea que requiere que elimine algunos datos en una matriz que está en un archivo JSON, usando node/express. Quiero, cuando se realiza una solicitud de eliminación, eliminar un elemento específico que coincida con una identificación específica en la matriz que está en el archivo JSON. Intenté usar el método de filtro, pero parece que no funciona.

archivo JS:

 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") })

Archivo/datos JSON:

 {"projects":[{"id":"1","game":"miniGame"},{"id":"2","game":"min"}]}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

La función de filter no cambia la matriz, por lo que debe volver a asignar los elementos filtrados a la matriz.

 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) }) })
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda