webdesignnoob
webdesignnoob

Reputation: 391

Assignment in a map function?

I have something like this:

this.array1 = this.array1.map(a => (a.name = "Harold"));

The syntax is wrong and I’m unsure why. What I’m trying to do is: For every object in array1, I want "name" to be Harold.

The array is structured similar to this:

array1 = [
    {
        name: "ashley",
        last: "bob"
    },
    {
        name: "tiny",
        last: "tot"
    }
]

The error I get is:

Arrow function should not return assignment

The results I want is an array that is like:

array1 = [
    {
        name: "Harold",
        last: "bob"
    },
    {
        name: "Harold",
        last: "tot"
    }
]

Upvotes: 0

Views: 2217

Answers (3)

ElChiniNet
ElChiniNet

Reputation: 2902

Array.prototype.map creates a new array taking as input the original array and returning in the callback the replacement of each item in the array.

You are not returning anything in your callback, you are just assigning a value, you could use the comma operator and return the same object already mutated:

this.array1 = this.array1.map(a => (a.name = "Harold", a));

Snippet:

const array1 = [{name: "ashley", last: "bob"}, {name: "tiny", last: "tot"}];

const array2 = array1.map(a => (a.name = "Harold", a));

console.log(array2);

Note: As others pointed out, you should not use map to mutate the original array. Either you should use a forEach to mutate the objects or you should return a new array without mutating the original one. What happens with your solution (and this small edition that I proposed) is that you end up with a second array containing the same mutated objects of the first array.

Upvotes: 0

Tushar Shahi
Tushar Shahi

Reputation: 20626

Arrow function should not return assignment

If you write your [arrow function] like below you are implicitly return whatever is inside the brackets. In this case it is an assignment. See the first demo on this page.

this.array1 = this.array1.map(a => (a.name = "Harold"));

How map works is you have to return the object you want as an element in your Array. Below i am explicitly returning a.

this.array1 = this.array1.map(a => {
a.name = "Harold";
return a;});

Remember, you could have used should use forEach here too. From the documentation, map creates a new array populated with the results of calling a provided function on every element in the calling array.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386736

You could spread the object and add another name for all object.

This method does not mutate the given data.

const
     array1 = [{ name: "ashley", last: "bob" }, { name: "tiny", last: "tot" }],
     array2 = array1.map(object => ({ ...object, name: "Harold" }));

console.log(array2);

Upvotes: 2

Related Questions