Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 503
Rolando Avatar asked Jul 03 '17 20:07

Rolando


2 Answers

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 your for loop seems the best way to do it. Otherwise you could for instance go for filter and forEach:

myarray.filter(someobject => someobject.key == 'B')
       .forEach(someobject => someobject.mark = "marked!")
like image 162
trincot Avatar answered Oct 10 '22 16:10

trincot


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'; });
like image 29
Bergi Avatar answered Oct 10 '22 16:10

Bergi