[英]Using Array.map() on array of objects
我試圖使用Array.map來切片數組中每個對象的description
屬性。
docs = docs.map(function(currentValue, index, array){
currentValue['description'] = currentValue.description.slice(0,10);
return array;
});
當我console.log(docs)
它似乎已經工作了。 但是,由於某種原因,我無法再訪問屬性。
console.log(docs[0].description); //undefined
看來我已經將對象數組變成了看起來像對象的字符串數組。 有什么想法嗎?
.map
的回調不應返回array
,而應返回您希望數組中的特定項具有的新值。
docs = docs.map(function(item){
item.description = item.description.slice(0, 10);
return item;
});
如果您要做的只是轉換數組中的每個項目,則改用.forEach
會更.forEach
。 .map
創建一個全新的數組 ,而.forEach
只是循環遍歷現有數組。 它也需要更少的代碼。
docs.forEach(function(item){
item.description = item.description.slice(0, 10);
});
這是因為您在map中而不是currentValue
返回了array
。 它應該是
docs = docs.map(function(currentValue, index, array){
currentValue['description'] = currentValue.description.slice(0,10);
return currentValue;
});
docs = docs.map(function(currentValue, index, array){
docs[index]['description'] = currentValue.description.slice(0,10);
return array;
});
我認為應該是這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.