0

I have a question regarding copy of object by reference

I have a small snippet demonstrating the problem I want to not mutate the initial object I can do it by using immutable.js or some library, but I am wondering how it can be done with native 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>
partizanos
  • 1,064
  • 12
  • 22

1 Answers1

0

use this way:

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);
Behnam
  • 6,244
  • 1
  • 39
  • 36