简体   繁体   中英

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.

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. 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.

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. .map creates a whole new array , whereas .forEach simply loops through the existing array. 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 . 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

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.

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

I think it should be like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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