-3

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)
 }
});
mikkel
  • 11
  • 3
  • Your test if the provided `kategori` is in `besatning` (which is an array of objects) will not work. You need to [compare](https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e) it to the `kategori` property of the individual objects in the array. – jarmod Nov 04 '21 at 20:34
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Nov 05 '21 at 09:55

1 Answers1

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 }

Jamie Nicholls
  • 55
  • 1
  • 10