对对象数组使用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
会更具性能。.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;
});
我觉得应该是这样。
相关文章:
- 为什么可以't我用Set对象调用Array.prototype.map
- 将Javascript响应转换为Array/Map
- Array.map() and D3 selection?
- 为什么 Array.prototype.reduce() 不接受 Map 对象作为初始值
- Array.from 在 Array#map 中不能用作直接回调函数
- 在 Array.map() 中调用类方法
- 如果 Array.prototype.map() 没有返回,它是否被正确使用
- ESLint prefer-arrow-callback on array.map
- Array.map没有'似乎无法处理未初始化的数组
- 为什么使用Array.prototype.map.call而不是Array.map.call
- Array.map 希望将值映射到无
- (new Array(10)).map(function() { return 1;}) 返回 [, , , , , .
- Array.map 和 Javascript 中的提升函数
- [].map.call() VS Array.prototype.map.call()?
- 正在使用 Array.map 作为 foreach 的良好做法
- 为什么 Array.map 似乎不适用于未定义值的数组
- 使用类似于 Array.prototype.map() 的方法将数组转换为键值对象
- 等待 array.map 等待中的异步进程
- JavaScript: parseInt's radix mystery with Array.map
- IE11 中的 Array.map() 出错