簡體   English   中英

在對象數組上使用Array.map()

[英]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;
    });

在這種情況下,您需要使用的是forEach()而不是map(),因為您沒有對數組中的項目進行任何轉換

docs.forEach(function(currentValue, index, array){
    currentValue['description'] = currentValue.description.slice(0,10);
});

.map()用於轉換數組中的每個項目並返回一個新對象,因為在您的情況下,您只是更改每個項目的屬性,因此無需使用它。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM