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

160
Visualizações
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 Respostas
Responde à pergunta

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 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