POV
POV

Reputation: 12015

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;
        }));

Upvotes: 1

Views: 3801

Answers (4)

Samuel_NET
Samuel_NET

Reputation: 365

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.

Upvotes: 1

wentjun
wentjun

Reputation: 42556

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.

Upvotes: 2

Motassem Kassab
Motassem Kassab

Reputation: 1815

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.

Upvotes: 1

Teneff
Teneff

Reputation: 32158

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)

Upvotes: 1

Related Questions