2017-02-14 39 views
2

將一個新屬性添加到數組中存在的對象我試圖有條件地使用.map()向數組中的對象添加屬性,但我似乎缺少一些東西。地圖完成後,我的對象數組保持不變。所有這些都是試圖解決ESLint錯誤'no-param-reassign'的結果,如果這有助於理解我爲什麼要這樣做。使用.map()

我已經做了一個我試圖在這裏完成的簡單例子: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); 
+3

'.MAP()'不發生變異原。它創建一個新的數組,返回,所以'var newMap = aList.map(...' – 2017-02-14 18:07:03

回答

4

,因爲你不使用的Array#map結果您可以使用Array#forEach

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