0

We use the delete when we need to delete the object reference. But is there any way in JS to delete the entire object and all references?

Example:

let obj = {
    a: 3
}
let arr = [obj];
let brr = [obj];

If I'd change the obj items in the arrays would be changed too. Also, I can use delete arr[0] to delete the reference. But I want to delete the obj and I want the items in the arrays to be deleted too.

Something like:

// Before: 
let obj = {
   a: 3
}
let arr = [obj];
let brr = [obj];
arr.length==1 // true
brr.length==1 // true
// Deleting:
delete(obj)
// After:
arr.length==0 // true
brr.length==0 // true
misterbobot
  • 92
  • 1
  • 7
  • afaik there is no mecanism allowing this in javascript – jonatjano Dec 24 '21 at 11:05
  • 4
    [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - What is the actual problem you try to solve with this? – Andreas Dec 24 '21 at 11:06
  • Thank you, @Andreas, I've done the edit – misterbobot Dec 24 '21 at 11:13
  • I recommend you to read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management – HDM91 Dec 24 '21 at 11:13
  • The only way to do this if you use some sort of data management library such as React, or RxJS. Then, when an object is removed, the arrays are regenerated and will become empty. – Kokodoko Dec 24 '21 at 11:13
  • 1
    Probably you want [javascript - Removing all properties from a object - Stack Overflow](https://stackoverflow.com/questions/19316857/removing-all-properties-from-a-object) instead. Not exactly what you want but we don't understand what you reallyi want at all. – user202729 Dec 24 '21 at 11:15
  • Yeah, it seems like the closest thing I can do is delete the properties – misterbobot Dec 24 '21 at 12:56

1 Answers1

2

No.

The only way to delete an object in JavaScript is to locate and delete each reference to it.

There's no generic mechanism to start with an object and automatically delete all references to it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335