[英]How to remove reference from object in JavaScript
我在 ractive.js 中有一個應用程序,我需要從我的組件 state 創建一些數據的副本。 例子:
const dateGroups = this.get("dateGroups");
this.set("editedPickups.beforeEdit", dateGroups);
而且我需要從“editedPickups.beforeEdit”中刪除針對“dateGroups”的引用,因為如果我在“dateGroups”中更改某些內容,它也會在“editedPickups.beforeEdit”中更改。 我找到了JSON.stringify
和parse
的解決方案,但是這個 object 很大,我不知道這會是誰演的。 下面的這個例子也不起作用:
const dateGroups = Object.assign({}, this.get("dateGroups"));
您發布的示例將不起作用,因為 Object.assign 將淺拷貝 object (嵌套道具仍將保留對原始對象的引用)。 您可以使用lodash.cloneDeep()
。
您可以使用傳播語法來創建新的即時
// 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
使用 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.