Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  110] [ 5]  / answers: 1 / hits: 6365  / 8 Years ago, mon, july 25, 2016, 12:00:00

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?


More From » json

 Answers
4

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.


[#27141] Saturday, July 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbyw

Total Points: 456
Total Questions: 102
Total Answers: 113

Location: Bahrain
Member since Fri, Sep 16, 2022
2 Years ago
;