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

Tyl*_*ler 2 javascript arrays

我正在尝试使用 Array.map 对description数组中每个对象的属性进行切片。

docs = docs.map(function(currentValue, index, array){
            currentValue['description'] = currentValue.description.slice(0,10);
            return array;
        });
Run Code Online (Sandbox Code Playgroud)

当我console.log(docs)看起来好像它已经起作用了。但是,由于某种原因,我无法再访问这些属性。

console.log(docs[0].description); //undefined
Run Code Online (Sandbox Code Playgroud)

看来我已经把我的对象数组变成了一个似乎是对象的字符串数组。有什么想法吗?

Rob*_*bin 5

回调.map不应返回array——它应该返回您希望数组中的特定项目具有的新值。

docs = docs.map(function(item){
  item.description = item.description.slice(0, 10);
  return item;
});
Run Code Online (Sandbox Code Playgroud)

如果您所做的只是转换数组中的每个项目,那么使用它会更.forEach高效。.map创建一个全新的数组,而.forEach只是循环遍历现有数组。它还需要更少的代码。

docs.forEach(function(item){
  item.description = item.description.slice(0, 10);
});
Run Code Online (Sandbox Code Playgroud)