2

How would one go about cloning an object that has arrays in it with the new spread operator?

Example Object:

vehicles: { 
  cars:  [1, 2],
  boats: [3, 4]
}

I want a new object with the arrays in it. In that new object I want to be able to change or add to an array without it referencing and effecting vehicles object.

4

2 回答 2

3

Object.assign 和扩展运算符创建浅克隆,只有一层深,超出了它们的引用。我发现的最好方法(感谢MDN)是使用 JSON 函数来创建一个真正的克隆。

let vehicles = { 
  cars:  [1, 2],
  boats: [3, 4],
};

let test = JSON.parse(JSON.stringify(vehicles));

console.log(vehicles, test);

test.cars[0] = 5;
vehicles.cars[0] = 7;

console.log(vehicles, test);

于 2017-10-19T18:07:55.703 回答
1

如果您正在寻找性能,使用 JSON.parse(JSON.stringify(object)) 进行深度复制和对象不是最好的方法,而是使用这样的深度复制:

let x1 = {
  numbers: {
    number: 1
  }
}
let y1 = copy(x1)
x1.numbers.number++
  console.log(x1)
console.log(y1)

function copy(aObject) { // Deep Clone Object from https://stackoverflow.com/a/34624648/16642626
  if (!aObject) {
    return aObject;
  }

  let v;
  let bObject = Array.isArray(aObject) ? [] : {};
  for (const k in aObject) {
    v = aObject[k];
    bObject[k] = (typeof v === "object") ? copy(v) : v;
  }

  return bObject;
}

于 2021-12-04T20:31:24.313 回答