最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

json - Javascript push object as clone - Stack Overflow

programmeradmin7浏览0评论

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?

Share Improve this question asked Jul 25, 2016 at 10:34 XenthorXenthor 4436 silver badges12 bronze badges 1
  • 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
Add a ment  | 

2 Answers 2

Reset to default 14

If 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.

发布评论

评论列表(0)

  1. 暂无评论