在JavaScript中,基于ID替换对象数组中的特定对象

4
我有一个对象数组,就像这个例子。
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数组中对象的内容?

通过ID搜索对象并更新内容。您可以使用Underscore JS来完成此操作。 - mastermind
@mastermind,完全不需要使用 underscore.js 来完成这个。 - quirimmo
5个回答

7

您可以搜索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的参数,因为可能只有一个属性需要更新。


这是正确的答案。它不引入不必要的循环,使简单逻辑变得模糊。 - Martin

1
你可以将对象作为参数传递给函数,并使用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)


1
最好传递一个仅包含更改内容的对象(一个仅包含要更改值的属性或属性的对象)。
通常,您可以按如下方式操作;

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;
}

是微不足道的。


0
仅更新已更改的值。
如果新书的id不存在,将添加新书,并且如果新书具有未定义的值,则将这些值设置为未定义。

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; }


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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接