Rolando
Rolando

Reputation: 62674

How to use map/filter to modify contents of an array of objects?

I have the following array:

myarray = [
    { "key": "A" },
    { "key": "B" }
]

How can I use a map/filter function in JavaScript to do the equivalent of:

for (var i = 0; i < myarray.length; i++) {
    if ( myarray[i].key == 'B') {
        myarray[i].mark = "marked!"
    }
}

In my attempt, I don't get the mark property in the output:

myarray.filter((someobject) => someobject.key == 'B').mark = "marked!"
console.log(myarray) // this does not show the "mark" key.

NB: I want to modify the original array.

Upvotes: 16

Views: 51290

Answers (2)

trincot
trincot

Reputation: 350831

If there is exactly one match, then you can use find:

myarray.find(someobject => someobject.key == 'B').mark = "marked!"

If you don't know the number of matches, then a for loop seems the best way to do it -- but use the for..of syntax:

for (const obj of myarray) {
    if (obj.key === 'B') {
        obj.mark = "marked!";
    }
}

Otherwise you could for instance go for filter and forEach:

myarray.filter(someobject => someobject.key == 'B')
       .forEach(someobject => someobject.mark = "marked!")

Upvotes: 38

Bergi
Bergi

Reputation: 665122

What is the best way so that I can make it such that I can use a map/filter function in javascript to do the equivalent of this code?

Not all, since neither map nor filter modify an array. They create new ones. You could use something like

let newArray = myArray.map(({key} => ({key, marked: key=='B'}));

but the best ES6 equivalent to your code is

for (let v of myArray) if (v.key == 'B') v.mark = 'marked';

You could also use forEach, but I heavily recommend against disguising side effects in a functional approach:

myArray.filter(({key}) => key == 'B').forEach(v => { v.mark = 'marked'; });

Upvotes: 5

Related Questions