I use d3 for a interactive network application. The data I need to bind changes during the interaction and consists of some selected objects from my JSON variable.
For that I used map on the JSON variable and made some queries to select the appropriate objects. The objects are pushed onto a list and this list is bound as new data.
My problem is, that Javascript pushes objects just as reference. While d3 makes some fancy data modifications my JSON variable gets messy and my queries won't work anymore.
Do I need to copy each object with something like JSON.stringify()
or jQuery.extend()
or is there a different solution to decouple my JSON variable from the array of objects I pass as data?
I use d3 for a interactive network application. The data I need to bind changes during the interaction and consists of some selected objects from my JSON variable.
For that I used map on the JSON variable and made some queries to select the appropriate objects. The objects are pushed onto a list and this list is bound as new data.
My problem is, that Javascript pushes objects just as reference. While d3 makes some fancy data modifications my JSON variable gets messy and my queries won't work anymore.
Do I need to copy each object with something like JSON.stringify()
or jQuery.extend()
or is there a different solution to decouple my JSON variable from the array of objects I pass as data?
-
1
Have a look at "What is the most efficient way to clone an object in JavaScript?". Using
stingify()
/parse()
isn't that bad an idea. It's not ideal and there are some issues that need special attention but it is probably the fastest candidate. – altocumulus Commented Jul 25, 2016 at 11:46
2 Answers
Reset to default 14If you only need a shallow copy you can do it like this:
arr.push({...o})
Assuming o is the object that you want to push and clone at the same time.
Every JS object is passed as a reference (objects, arrays, functions etc.). In order to make a 'deep copy' of a particular object you can do:
var deepCopy = JSON.parse(JSON.stringify(oldObject)) // 1. - more of a hack
var deepCopy = _.cloneDeep(oldObject); // 2. use some predefined methods from jQuery, lodash or any other library
var shallowCopy = Object.assign({}, oldObject) // 1. - preferred (if you support new ES features)
this way your data on the list won't be modified.