简体   繁体   English

如何从 JavaScript 中的 object 中删除参考

[英]How to remove reference from object in JavaScript

I have an application in ractive.js, and I need to create copy of some data from my component state.我在 ractive.js 中有一个应用程序,我需要从我的组件 state 创建一些数据的副本。 example:例子:

const dateGroups = this.get("dateGroups");
this.set("editedPickups.beforeEdit", dateGroups);

And I need to remove reference from "editedPickups.beforeEdit" which is targeted to "dateGroups" because if I change something in "dateGroups" it changes in "editedPickups.beforeEdit" too.而且我需要从“editedPickups.beforeEdit”中删除针对“dateGroups”的引用,因为如果我在“dateGroups”中更改某些内容,它也会在“editedPickups.beforeEdit”中更改。 I find solution with JSON.stringify and parse , but this object is big and I don't know who this will be acting.我找到了JSON.stringifyparse的解决方案,但是这个 object 很大,我不知道这会是谁演的。 This example below not working too:下面的这个例子也不起作用:

const dateGroups = Object.assign({}, this.get("dateGroups"));

The example you've posted won't work because Object.assign will shallow copy the object (nested props will still hold references to the original object).您发布的示例将不起作用,因为 Object.assign 将浅拷贝 object (嵌套道具仍将保留对原始对象的引用)。 You can use lodash.cloneDeep() .您可以使用lodash.cloneDeep()

You can use spread syntax to create new instant您可以使用传播语法来创建新的即时

// if dateGroups is an array
this.set("editedPickups.beforeEdit", [...dateGroups]);
// if dateGroups is an object
this.set("editedPickups.beforeEdit", {...dateGroups});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

With ES6, you can remove an object reference by using the ... syntax.使用 ES6,您可以使用...语法删除 object 引用。

 const objectWeWantToCopyButNotReference = { foo: 'bar' } const myNewObject = {...objectWeWantToCopyButNotReference } myNewObject.foo = 'not bar' console.log('my new object has changed:', myNewObject.foo) console.log('original object not changed: ', objectWeWantToCopyButNotReference.foo)

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

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