Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a particular object based on id in an array of objects in javascript

I have an array of objects like this one.

var books = [{
id : 1,
name : 'Name of the wind',
year : 2015,
rating : 4.5,
author : 2}];

Now I have a function editBooks which asks user for an id and replaces the book with same id with the values given by the user. For example

function editBooks(name,author,year,rating,id)

How can i replace the contents of objects inside my books array based on id provided by the user?

like image 378
Shehzadi khushi Avatar asked Sep 06 '25 22:09

Shehzadi khushi


2 Answers

You could serach for the id and use the book for update. If no book is found, generate a new entry.

function editBooks(name, author, year, rating, id) {
    var book = books.find(b => b.id === id);
    if (book) {
        book.name = name;
        book.author = author,
        book.year = year;
        book.rating = rating;
    } else {
        books.push({ id, name, author, year, rating });
    }
}

var books = [{ id: 1, name: 'Name of the wind', year: 2015, rating: 4.5, author: 2 }];

editBooks('Foo', 2017, 3.3, 5, 1);
editBooks('bar', 2016, 1, 2, 2);
console.log(books);

For a slightly better implementation, i would move id to the first place of the parameters and use a check for all parameters to update only the ones who are not undefined, because aof a possible update of only one property.

like image 173
Nina Scholz Avatar answered Sep 09 '25 15:09

Nina Scholz


You could pass object as parameter to your function and use for...in loop to update object with same id if found.

var books = [{id: 1,name: 'Name of the wind',year: 2015,rating: 4.5,author: 2}];

function editBooks(obj) {
  books.forEach(function(e) {
    if(obj.id && obj.id == e.id) {
      for(var i in obj) e[i] = obj[i]
    }
  })
}

editBooks({id:1, name: 'New name', author: 22})
console.log(books)
like image 45
Nenad Vracar Avatar answered Sep 09 '25 15:09

Nenad Vracar