• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

127
Views
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)
 }
});
almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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 }

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error