She*_*shi 3 javascript arrays loops javascript-objects
我有一系列像这样的对象。
var books = [{
id : 1,
name : 'Name of the wind',
year : 2015,
rating : 4.5,
author : 2}];
Run Code Online (Sandbox Code Playgroud)
现在我有一个函数 editBooks,它要求用户提供一个 id 并用用户提供的值替换具有相同 id 的书。例如
function editBooks(name,author,year,rating,id)
Run Code Online (Sandbox Code Playgroud)
如何根据用户提供的 id 替换我的 books 数组中对象的内容?
您可以搜索id并使用本书进行更新。如果没有找到书,则生成一个新条目。
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);Run Code Online (Sandbox Code Playgroud)
为了稍微好一点的实现,我将移到id参数的第一个位置并使用对所有参数的检查来仅更新那些不是的参数undefined,因为可能只更新一个属性。