Search code examples
javascriptarraysobjectbabeljs

Adding a new property to an Object that exists in an Array, using .map()


I'm trying to conditionally add a property to an object in an array using .map(), but I seem to be missing something. My array of objects remains unchanged after the map is complete. All of this is the result of trying to resolve the ESLint error 'no-param-reassign' if that helps understand why I'm doing this.

I've made a rudimentary example of what I'm trying to accomplish here: 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);

Solution

  • You could use Array#forEach, because you are not using the result of 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; }

    For an all new array, you could use Array#map and use the result of it. For adding a new property to an object, you could use Object.assign, which mutates and returns the object at the first parameter.

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