3

I have an array of members in Typescript.

const members = [
  {
    name: 'John Lennon',
    id: 1
  },
  {
    name: 'Led Zeppelin',
    id: 2
  },
  {
    name: 'Freddie Mercury',
    id: 3
  }
];

When I try to map over it and add key

members.map(member => {
    member.designation = 'Singer';
    return member;
 });

It successfully overwrites an array and add key designation. But when I try doing the same thing using Object spread operator.

members.map(member => ({
  ...member,
  designation: 'Singer'
}));

It successfully compiles with no error, but at the same time does not map the key designation over my members array.

Is it the correct way to do, or am I missing something and it is just a problem with Typescript Object spread operation.

1
  • why do you have to use parentheses in the 2nd map call? I mean : member => ({... and not member => {...? I tried without parentheses and I got an error but I don't understand why... Commented Aug 31, 2020 at 8:42

1 Answer 1

7

In the first example you modify the object, in the second one you create a new object, that will have the values of the original member and the new designation property. You need to take the new object array created by map and use that:

var memberWithDesignation = members.map(member => ({
  ...member,
  designation: 'Singer'
}));
console.log(memberWithDesignation[0].designation); // Will output Singer
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.