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.
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!")
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'; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With