使用对象复制对象,避免初始对象的变异(避免复制引用)

时间:2017-07-11 12:45:24

标签: javascript json deep-copy

我有一个关于通过引用复制对象的问题

我有一个小片段,演示了我想通过使用immutable.js或某些库来改变我可以做的初始对象的问题,但我想知道如何使用原生js。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

/////////// object Create 
let a = {
  "0": {

    "sortPluginSettings": {
      "columnSortType": "numeric",
      "sortingOrder": "noSort"
    }
  }
}
let b= Object.create(a)
console.log("a: ",a)
console.log("b: ",b)

b["0"].sortPluginSettings.sortingOrder="ascending"
console.log("NEWa: ",a) // OOPs mutated
console.log("NEWb: ",b[0])

/////////// object assign
let c = {
  "0": {

    "sortPluginSettings": {
      "columnSortType": "numeric",
      "sortingOrder": "noSort"
    }
  }
}
let e= Object.create(c)
console.log("c: ",c)
console.log("e: ",e)

e["0"].sortPluginSettings.sortingOrder="ascending"
console.log("NEWc: ",c) // OOPs mutated
console.log("NEWe: ",e[0])
</script>
    <title></title>
</head>
<body>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用这种方式:

let a = {
  "0": {
    "sortPluginSettings": {
      "columnSortType": "numeric",
      "sortingOrder": "noSort"
    }
  }
}

var b= JSON.parse(JSON.stringify(a));

b[0].sortPluginSettings.columnSortType=null;

console.log(a);
console.log(b);