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

424
Vistas
how to update properly an json´s object?

I´m learning backend using node.js, so I´m developing a API RESTfull. I need to use PUT to update a object by id (the id as a params) in a json file. I´m using postaman to test.

This is my array:

[
  {
    "item": "phone",
    "price": 10000,
    "id": 1
  },
  {
    "item": "tv",
    "price": 20000,
    "id": 2
  },
  {
    "item": "nintendo",
    "price": 2500000,
    "id": 3
  },
  {
    "item": "ipad",
    "price": "500000",
    "id": 4
  }
]

For example I a have a local server http://127.0.0.1:8080/products/3 (the number 3 will be the item I wanna update changing the price or the name).

I started like this

app.put("/products/:id", (request, resolve) => {
  const id = Number(request.params.id);



})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

in a JSON file, you need to rewrite your data every time you update data

const data = require("./<fileName>.json"); // bring your json file
const fs = require("fs"); // fileModule to updata your json file

app.put("/products/:id", (request, resolve) => {
  const id = Number(request.params.id);

  let idx = data.findIndex(e=>e.id===id);// getting index of data by matching your id
  if(!idx){
    return resolve.json({message:"data not found"});
  }

  data[idx] = {} // your new data with id, you will get this data from request.body

  fs.writeFile("./<fileName>.json",JSON.stringify(data),(err)=>{  // writing updated data in your json fil
    if(err){
      return resolve.json({message:err}); // if you get ant error
    }
  });

  resolve.json(JSON.stringify(data)); // send response 
})

note:this is not the synchronous way of writing JavaScript. if you like my answer don't forget to upvote and follow.

about 4 years ago · Juan Pablo Isaza 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