使用.map()将新属性添加到Array中存在的Object

Tyl*_*r H 3 javascript arrays object babeljs

我试图使用.map()有条件地将属性添加到数组中的对象,但我似乎错过了一些东西.地图完成后,我的对象数组保持不变.所有这一切都是尝试解决ESLint错误'no-param-reassign'的结果,如果这有助于理解我为什么这样做.

我已经为我在这里要完成的事情做了一个基本的例子:jsfiddle.

var aList = [{
    Title: "Enders Game",
    Rating: 8
  },
  {
    Title: "Harry Potter",
    Rating: 10
  }];

console.log('before', aList);

aList.map(function(book) {
    if(book.Title == "Enders Game"){
    console.log({ ...book, completed: true })
    return { ...book, completed: true };
  }
  console.log({ ...book, completed: false })
  return { ...book, completed: false };
});

console.log('after', aList);
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 5

您可以使用Array#forEach,因为您没有使用结果Array#map.

var aList = [{ Title: "Enders Game", Rating: 8 }, { Title: "Harry Potter", Rating: 10 }];

aList.forEach(function(book) {
    book.completed = book.Title == "Enders Game";
});

console.log(aList);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

对于全新的数组,您可以使用Array#map使用它的结果.要向对象添加新属性,可以使用Object.assign,在第一个参数处进行变异并返回对象.

var aList = [{ Title: "Enders Game", Rating: 8 }, { Title: "Harry Potter", Rating: 10 }],
    newList = aList.map(book => Object.assign({}, book, {completed: book.Title == "Enders Game"}));

console.log(aList);
console.log(newList);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)