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

164
Vistas
How can i change my array with a put request

When i try to change my objects in my array it wont work. I want to be able to call it in postman with the a new value attahed to the item i call. please help, it's an assignment for today

screenshot from postman

const express = require("express");
const {emitWarning} = require("process");
// laver en variabel hvor sætter en execution af express til den
const app = express()
//Nedenunder laver jeg en port med nummer 8080 som vil bruges igennem hele opgaven
const PORT = 8081;
//bruger console.log til at printe beskeden og det gør jeg ved hjælp af en listen method
app.listen(PORT, () => console.log("server lytter på port 8080"))


//Opgave B
//jeg laver min array hvor jeg putter kategorierne ind samt antallet til hver kategori
var besatning = [

  {id:0, kategori: 'Køer', antal: 50 },
   {id:1, kategori: 'Hunde', antal: 1 },
   {id:2, kategori: 'Grise', antal: 100 },
   {id: 3, kategori: 'Får', antal: 20 },
];
app.put('/ny_besætning/:kategori/:antal', (req, res)=> {
 if (req.params.kategori in besatning){
   besatning[req.params.kategori] = req.params.antal;
   res.json(besatning);
 } else{
   res.sendStatus(404)
 }
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It looks like your trying to access an array of objects as if it was an array of strings.

Try and change this:

 if (req.params.kategori in besatning){
   besatning[req.params.kategori] = req.params.antal;
   res.json(besatning);
 } else{
   res.sendStatus(404)
 }

To this

const result = besatning.find(item => item.kategori === req.params.kategori);
if (result) {
    res.json(result);
} else {
    res.sendStatus(404);
}

This will return the matching item. And should be called with a GET request.

PUT requests are to update an item, generally by an id. Your url be something like "/ny_besætning/:id" and then use the find filter to get the item based on the id. When updating the item, it should be done via a the payload (i.e. in postman its the body tag) in the format of a full object i.e: {id:0, kategori: 'updated', antal: 9999 }

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