You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复制对象内数组并修改后原对象被更新的解决方法

Ah, I get it—you've run into the classic shallow copy vs deep copy issue in JavaScript! Let me break down why this is happening first, then give you a few solid fixes.

Why your current code isn't working

When you use values.pieces.slice(), you’re creating a new array, but the objects inside that array are still just references to the original objects in values.pieces. So when you update pieces[0].width, you’re modifying the exact same object that’s still pointed to by the original array.


Fix 1: Use map() with object spread (best for simple objects)

You can iterate over the original array and create a fresh copy of each object using the spread operator (...). This gives you a new array with entirely independent objects:

const values = { pieces: [ { width: 15 } ] };
const pieces = values.pieces.map(piece => ({ ...piece }));

pieces[0].width = 21;
console.log(values.pieces[0].width); // 15 (original stays intact!)
console.log(pieces[0].width); // 21 (new array is updated)

If you prefer, you can use Object.assign() instead for the same effect:

const pieces = values.pieces.map(piece => Object.assign({}, piece));

Fix 2: JSON serialization/deserialization (quick for plain structures)

If your objects don’t contain functions, undefined values, or circular references, this one-liner works perfectly:

const values = { pieces: [ { width: 15 } ] };
const pieces = JSON.parse(JSON.stringify(values.pieces));

pieces[0].width = 21;
console.log(values.pieces[0].width); // 15

Note: This method strips out any non-JSON-safe values (like functions), so only use it for plain data objects.

Fix 3: Custom deep copy function (for complex nested objects)

If you need to handle nested objects or more intricate data structures later, a recursive deep copy function will handle everything properly:

function deepCopy(obj) {
  // Return primitive values as-is (strings, numbers, booleans, etc.)
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  // Handle arrays by copying each element recursively
  if (Array.isArray(obj)) {
    return obj.map(item => deepCopy(item));
  }

  // Handle plain objects by copying each key-value pair
  const copiedObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      copiedObj[key] = deepCopy(obj[key]);
    }
  }
  return copiedObj;
}

const values = { pieces: [ { width: 15 } ] };
const pieces = deepCopy(values.pieces);

pieces[0].width = 21;
console.log(values.pieces[0].width); // 15

Pick the method that fits your use case: for simple objects like your example, Fix 1 is clean and efficient. If you need to handle nested structures down the line, go with Fix 3.

内容的提问来源于stack exchange,提问作者prajeesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:32:45