简体   繁体   English

Javascript 推送对象作为克隆

[英]Javascript push object as clone

I use d3 for a interactive network application.我将 d3 用于交互式网络应用程序。 The data I need to bind changes during the interaction and consists of some selected objects from my JSON variable.我需要绑定的数据在交互过程中发生了变化,并且由我的 JSON 变量中的一些选定对象组成。
For that I used map on the JSON variable and made some queries to select the appropriate objects.为此,我在 JSON 变量上使用了 map 并进行了一些查询以选择适当的对象。 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.我的问题是,Javascript 将对象作为参考推送。 While d3 makes some fancy data modifications my JSON variable gets messy and my queries won't work anymore.虽然 d3 进行了一些花哨的数据修改,但我的 JSON 变量变得混乱,我的查询将不再起作用。
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?我是否需要使用JSON.stringify()jQuery.extend()类的东西复制每个对象,或者是否有不同的解决方案来将我的 JSON 变量与我作为数据传递的对象数组分离?

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.假设 o 是您要同时推送和克隆的对象。

Every JS object is passed as a reference (objects, arrays, functions etc.).每个 JS 对象都作为引用传递(对象、数组、函数等)。 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.这样您在列表中的数据就不会被修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM