I have an array that looks something like this:
[ [ {Obj}, {Obj}, {Obj} ], [ {Obj}, {Obj}, {Obj} ] ... ]
And I have an incoming Object which should replace one of the Objects in the array. I can find an Object I want to replace with a for loop, using id
property and replace it directly:
function findObject(arr, target) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j].id === target.id)
arr[i][j] = target;
}
}
}
findObject(arr, target);
// do stuff with arr
How can I achieve the same results without mutating the original array, preferably returning new array with merged object within one function?
Here is the js fiddle for convenience: https://jsfiddle.net/tnpxh8fy/