我有一个像这样的对象数组。
var books = [{
id : 1,
name : 'Name of the wind',
year : 2015,
rating : 4.5,
author : 2}];
现在我有一个函数editBooks,它询问用户的id并用相同的id替换用户给出的值的书。 例如
function editBooks(name,author,year,rating,id)
如何根据用户提供的id替换books数组中对象的内容?
答案 0 :(得分:3)
您可以搜索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);

为了稍微好一点的实现,我会将id
移到参数的第一位,并使用对所有参数的检查来仅更新非undefined
的参数,因为可能的更新只有一处房产。
答案 1 :(得分:1)
您可以将object作为参数传递给您的函数,并使用for...in
循环来更新具有相同ID的对象(如果找到)。
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)

答案 2 :(得分:0)
尝试以下代码段,
function editBooks(name,author,year,rating,id) {
var found = false;
books.forEach(function(book) {
if(book.id == id) {
book.name = name;
book.year = year ;
book.author = author;
book.rating = rating;
found = true;
}
});
return found; // if found is false, then you can insert new book
}
答案 3 :(得分:0)
最好传递一个只包含更改的对象(一个只包含一个或多个属性的对象来更改它们的值)
一般情况下,您可以按照以下步骤进行操作;
var books = [{id : 1, name : 'Name of the wind', year : 2015, rating : 4.5, author : 2}, {id : 2, name : 'River Guard', year : 2016, rating : 6.5, author : "John Doe"}];
Object.assign(books.find(b => b.id === 2),{author: "Jane Doe"});
console.log(books);

转入类似
的功能function editBook(bookList, id, edits){
Object.assign(bookList.find(b => b.id === id),edits);
return bookList;
}
是微不足道的。
答案 4 :(得分:0)
仅更新更改的值。
如果他们的ID不存在,并且如果新书有,则会添加新书 未定义的值将这些值设置为undefined。
var books = [
{
id : 1,
name : 'Name of the wind',
year : 2015,
rating : 4.5,
author : 2},
{id:2,
name : 'Name of the 2',
year : 2015,
rating : 4.5,
author : 2},
{id:3,
name : 'Name of the 3',
year : 2015,
rating : 4.5,
author : 2}
];
function editBooks(books,id,name,year,rating,author){
const update = book => Object.assign(book, { id:book.id,name: name || book.name,year: year || book.year,rating: rating || book.rating,author: author || book.author});
let details = books.find((book)=>{ return book.id===id });
details ? update(details):books.push({id,name ,year,rating, author});
};
//edit if exists
editBooks(books,2,'Updated Title','1985');
// add if id does not exist
editBooks(books,4,'A Whole New Title', 2015 );
console.log(books)

.as-console-wrapper { max-height: 100% !important; top: 0; }