对对象数组使用Array.map()

Using Array.map() on array of objects

本文关键字:map Array 对象 数组      更新时间:2023-09-26

我正在尝试使用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会更具性能。.map创建一个全新数组,而.forEach只是在现有数组中循环。它还需要更少的代码。

docs.forEach(function(item){
  item.description = item.description.slice(0, 10);
});

这是因为在映射中返回array而不是currentValue。应该是

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

我觉得应该是这样。