Home > front end >  angluarjs delete original object after full copy to a new object
angluarjs delete original object after full copy to a new object

Time:03-08

I have a large JSON that I load into my app via a <script> tag. the JS file that contains the JSON is about 280k. It is a standard JS definition:

var _countries = {"country:{"USA":{...},"GBR":{ ...},"FRA":( ...}, etc, etc ...}}} ;

It is loading into memory as the app launches and then I want to copy it to a new $rootScope variable, not just a reference to the original object, and then after its fully copied I want to delete the original _countries object.

$rootScope._countries= angular.copy(_countries) ;
_countries = null ;

But how can I tell when the object is fully copied before fully deleting the original _countries object? JS being asynchronous, I don't want to risk $rootScope._countries not having the full object before the null wipes out the original.

Also, is there a better way to copy the original object than using angular.copy() ?

CodePudding user response:

TLDR;

  • If this is really just a simple json assignment, you don't need to worry about waiting.
  • You also don't need to worry about deleting variables in JS to save memory.

Async

A simple data variable assignment like this will always be executed synchronously:

const foo = {...superBig} // definitely already just JSON

If you were reading from the JSON in the variable assignment, eg...

var _countries = funcToLoadJSON('path-to-my-json')

...that might be a different story depending on the implementation details since there are some methods that do that read synchronously and some that do it async. See examples.

Saving memory

You can't really delete any object in Javascript. JS engines try to figure out the “best” time to do garbage collection based on a handful of factors behind the scenes.

  • Related