Possibly this question has already been asked and answered a thousand times but I couldn't find it. Sorry :(
For the concept I have the following array in javascript (I am depicting the worst case szenario here):
var array1 = [{id: 8, text: "lala"},/* a lot of elements in between,*/ {id: 79, text: "lolo"}]
Now I would like to replace the element that has currently the id: 79 with Object {randomProperty1: "lulu"}. I don't want to replace the array afterwards as I use it as a reactive property in a reactive system like vuejs, so it should stay stateful. So I can't do something like:
array1 = array1.map(obj=>obj.id===79?{randomProperty1: "lulu"}:obj);
My naive approach so far is to do something like this:
const elem = array1.find(obj=>obj.id===79);
const index = array1.indexOf(elem);
array1[index] = {randomProperty1: "lulu"}
But now as I understand I would have to go through my array twice. Considering I have a huge array doing this operation every time my mouse moves, and maybe also having to recompute my new Object I felt better if I went only one time through my array. In every other case this would clearly be and maybe still is premature optimization but I'm interested in this.
My dream approach would be something like this (in pseudocode):
const elem = array1.find(o=>o.id===79);
elem = {randomProperty1: "lulu"}
But this obviously doesn't work as it is now call-by-value and not call-by-reference anymore.
The last (a bit ugly) approach I came up with is to change my array entirely like so:
var array2 = [{obj: {id: 8, text: "lala"}},/* a lot of elements in between,*/ {obj: {id: 79, text: "lolo"}}];
const elem = array2.find(o=>o.obj.id===79);
elem.obj = {randomProperty1: "lulu"}
So in short: Is there a better way to do it?
PS: I don't know it the tag 'vue-reactivity fit's here' - I don't know if this is a thing in angular or react as I don't know anything about those. My question just arose from vue-reactivity but I thought it could be generalized.