简体   繁体   English

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

[英]Using Array.map() on array of objects

I am trying to use Array.map to slice the description property of each object within an array. 我试图使用Array.map来切片数组中每个对象的description属性。

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

When I console.log(docs) it appears as though it has worked. 当我console.log(docs)它似乎已经工作了。 However, I can no longer access the properties for some reason. 但是,由于某种原因,我无法再访问属性。

console.log(docs[0].description); //undefined

It appears that I have turned my array of objects into an array of strings that appear to be objects. 看来我已经将对象数组变成了看起来像对象的字符串数组。 Any thoughts? 有什么想法吗?

The callback in .map shouldn't return array -- it should return the new value you want that particular item in the array to have. .map的回调不应返回array ,而应返回您希望数组中的特定项具有的新值。

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

If all you're doing is transforming each item in the array, it would be more performant to use .forEach instead. 如果您要做的只是转换数组中的每个项目,则改用.forEach会更.forEach .map creates a whole new array , whereas .forEach simply loops through the existing array. .map创建一个全新的数组 ,而.forEach只是循环遍历现有数组。 It also takes less code. 它也需要更少的代码。

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

It is because you return array in map instead of currentValue . 这是因为您在map中而不​​是currentValue返回了array It should be 它应该是

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

In that case, what you need to use is forEach() not map() as you are not doing any transformation of the items in the array 在这种情况下,您需要使用的是forEach()而不是map(),因为您没有对数组中的项目进行任何转换

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

.map() is used to transform each item in an array and return a new object, since in your case you are just changing a property of each item, there is no need to use it. .map()用于转换数组中的每个项目并返回一个新对象,因为在您的情况下,您只是更改每个项目的属性,因此无需使用它。

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

I think it should be like this. 我认为应该是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM