1

I wasn't able to find any answer to this particular question. Suppose I have an observable object that I would like to clone it into another completely independent variable and make this variable not observable. Could someone help me find a solution to this question?

I tried following a solution like this:

var notObservableVar = observableVar();

But the new variable doesn't appear to be independent since my subsequent code appears to work with observableVar and not a new independent one.

Razvan
  • 151
  • 4
  • 14
  • `var notObservableVar = Object.assign({}, observableVar());` – connexo Sep 09 '18 at 08:33
  • Thank you so much, this does appear to work. If you'd like, post a new answer for this question and I will accept the answer as the correct one. – Razvan Sep 09 '18 at 08:36
  • Please note that this creates a shallow copy. Observable properties of that object will still hold references. – connexo Sep 09 '18 at 08:39

1 Answers1

4

Update:

As thankfully stated by @Brother Woodrow in the comments, Knockout offers an API method .toJS() for the job:

var notObservable = ko.toJS(observableVar)

https://knockoutjs.com/documentation/json-data.html

Old answer (don't use this if your observable object has sub-observables):

To create a shallow copy of an object, you can useObject.prototype.assign():

var notObservableVar = Object.assign({}, observableVar());

The other option is to use Object destructuring:

var notObservableVar = {...observableVar()};

Please note that both methods require ES6 support - either in your buildstack (Babel), or in the browser that this is supposed to run in. Also note that for Object destructuring to work with Babel 6, you need a plugin (because Object destructuring was still a proposal when Babel 6 was the current version).

If ES6 is not available for you, you can use the old way of stringifying and then parsing the object:

var notObservableVar = JSON.parse(JSON.stringify(observableVar()));
connexo
  • 53,704
  • 14
  • 91
  • 128
  • Is there a possible way of creating a deep copy of the variable instead, to assure that there are no unexpected implications further down when using these variables? – Razvan Sep 09 '18 at 08:46
  • https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript?rq=1 – connexo Sep 09 '18 at 08:47
  • 2
    Note that Knockout actually has a built-in method `toJS` that does the same thing, but does not rely on `Object.assign`: `var notObservable = ko.toJS(observableVar)`. – Brother Woodrow Sep 09 '18 at 12:03
  • @BrotherWoodrow Does that also affect properties on an observable object which are defined as observables themselves? – connexo Sep 09 '18 at 12:31
  • Yes, that is exactly what the `toJS` method does. – Brother Woodrow Sep 10 '18 at 11:56