I don't like using map and looping to create a new array from an old array in JavaScript when just one item changes. I have a simple array that has data like this:
const speakerData = [{name: 'joe',id: 101,favorite: true},
{name: 'sam',id: 102,favorite: false},
{name: 'jon',id: 103,favorite: false}]
And I want to update record 102 to favorite is true (toggle favorite).
I have the following code that works:
const speakerId = 102;
const newSpeakerData = speakerData.map((rec) => {
if (rec.id === speakerId) {
rec.favorite = !rec.favorite;
return rec;
} else {
return rec;
}
});
I want something like what I have below but it obviously does not work.
const speakerRec = speakerData.find(a=>a.id === speakerId);
speakerRec.favorite = !speakerRec.favorite;
const newSpeakerData = [{...speakerData},speakerRec]
Is there a clever one line I can make this happen with ES7?