简体   繁体   中英

TypeScript - why is the spread operator used in map?

return items.map(item => ({
      ...item,
      score: Math.round((item.rate / 100) * 5)
    }));

I know that it changes score value for each object items . But why there is ...item ?

What is benefit to use it?

Is it equal to this?:

return items.map(item => ({
          item.score: Math.round((item.rate / 100) * 5);
          return item;
        }));

Using the spread operator is useful, if you want to create a shallow copy of the existing values, and update the object/array immutably .

One frequent usage of the spread syntax would be when you are using Redux for React.js or NgRX for Angular.

In the case of the code you have provided,

return items.map(item => ({
  ...item,
  score: Math.round((item.rate / 100) * 5)
}));

The resulting array will be a shallow copy of the items array alongside the original properties/values, followed by the updated values of the score property within each object of the items array.

It's equivalent to

Array.prototype.map.call(items, function(item) {
  return Object.assign({}, item, {
    score: Math.round((item.rate / 100) * 5)
  });
});

the idea of this approach is to create new array and for each item of the old create to create a new object containing all of the old's properties and a score property. If the score is present on the item (old array's entry it will be overwritten on the new object)

This is the spread operator, basically what the function is doing, is taking each item, mapping it to an object containing: a full clone of the item, and the score

{ item, score }

while your proposed function will only return the item object with an added attribute to it score , and also add that attribute to the element in the original items array, as you're modifying the referenced object, not a copy of it.

which to use? well that depends on your needs.

Similar to what previous answers suggest, notice that the spread operator is spreading the contents of item into another curly brace.

It's shallow copying the contents of item into that new object but replacing with the new value for score .

It is a memory efficient copy process and makes for very good code readability. It is similar to what you suggested.

It only provides better syntactic sugar in that context. I would advise you to consider using the spread operator a bit more if only for this purpose as well as its other use cases.

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