1

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/

curious_gudleif
  • 572
  • 1
  • 4
  • 19

2 Answers2

4

You should use .map, which creates a new array:

function findObject(arr, target) {
  return arr.map(function(users) {
    return users.map(function(user) {
      if (user.id === target.id) {
        return target;
      } else {
        return user;
      }
    });
  });
}
jehna1
  • 3,110
  • 1
  • 19
  • 29
1

Some copying will do the trick:

findObj = function(arrArrObj, needle) {
  var ret = Array.from(arrArrObj)
  for (let i in ret)
    for (let j in i)
      if (ret[i][j].id === needle.id) {
        ret[i] = Array.from(ret[i]) // as needed
        ret[i][j] = needle
        // break
      }
  return ret
}
Mingye Wang
  • 1,107
  • 9
  • 32