查找并替换多维 JS 数组中的元素 w/o 改变数组

Find and replace an element in a multidimensional JS Array w/o mutating the array

我有一个看起来像这样的数组:

[ [ {Obj}, {Obj}, {Obj} ], [ {Obj}, {Obj}, {Obj} ] ... ]

我有一个传入的对象,它应该替换数组中的一个对象。我可以找到一个我想用 for 循环替换的对象,使用 id 属性 并直接替换它:

  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

如何在不改变原始数组的情况下获得相同的结果,最好是在一个函数中返回带有合并对象的新数组?

为了方便起见,这里是 js fiddle:https://jsfiddle.net/tnpxh8fy/

一些复制就可以了:

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
}

您应该使用 .map,它会创建一个新数组:

function findObject(arr, target) {
  return arr.map(function(users) {
    return users.map(function(user) {
      if (user.id === target.id) {
        return target;
      } else {
        return user;
      }
    });
  });
}