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

时间:2017-02-14 18:04:02

标签: 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);

1 个答案:

答案 0 :(得分: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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

对于全新数组,您可以使用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);
.as-console-wrapper { max-height: 100% !important; top: 0; }