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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With