Gabriel Linassi
Gabriel Linassi

Reputation: 541

How to just change object property values that exists?

I'm creating a backend API and storing all data in a array for now because I'm still learning.

I need to update the object properties on the array based on a put request. I just want to replace the data requested by the client and the rest must remains the same.

I just know how to do it hard coding each property like Arr.propertyA = req.body.propetyA...

I want to know if there's a better way to do it.

Here is the code for clarity:

backend

const books = [
    {
        id: 1,
        title: 'Book 1',
        author: 'Author 1'
    },
    {
        id: 2,
        title: 'Book 2',
        author: 'Author 2'
    },
    {
        id: 3,
        title: 'Book 3',
        author: 'Author 3'
    }
]

app.put('/api/books/:id', (req, res) => {
    const foundIndex = books.findIndex(book => { return req.params.id == book.id });
    books[foundIndex] = req.body;

    res.send(books[foundIndex]);
}

front-end

PUT: 

url: http://localhost:5000/api/books/1

{
    "title": "New Book 1",
    "author": "New Author 1"
}

result:

{
    title: 'New Book 1',
    author: 'New Author 1'
}

but I expect

{
    id: 1,
    title: 'New Book 1',
    author: 'New Author 1'
}

============ EDIT ==================

Full function for better understanding

app.put("/api/books/:id", (req, res) => {
  const schema = {
    title: Joi.string()
      .min(3)
      .required(),
    author: Joi.string()
  };

  // Look up the course
  const book = books.find(book => {
    return req.params.id == book.id;
  });

  // If not existing, return 404
  if (book.length === 0) {
    res.status(404).send(`The book with ID: "${req.params.id}" was not found`);
    return;
  }

  // Validate
  const validation = Joi.validate(req.body, schema);

  // If invalid, return 400 - Bad request
  if (validation.error) {
    res.status(400).send(validation.error.details[0].message);
    return;
  }

  // Update the course
  Object.assign(book, req.body);

  // Return the updated course
  res.send(book);
});

Upvotes: 1

Views: 171

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

Once the matching id is found, use Object.assign to merge the req.body object onto the book. (Since you don't really care about the found index, only about the book object at that index, better to use .find than .findIndex):

app.put('/api/books/:id', (req, res) => {
    const book = books.find(book => { return req.params.id == book.id });
    Object.assign(book, req.body);
    res.send(book);
});

If there's any chance that there will not be a matching book for the req.params.id, make sure to check that book exists first before trying to do stuff with it.

If, like in your example, a book's id always matches its position in the books array, it would be easier to use bracket notation to just access the right index, instead of using .find:

app.put('/api/books/:id', (req, res) => {
    const book = books[req.params.id];
    Object.assign(book, req.body);
    res.send(book);
});

Upvotes: 1

Related Questions