1

I am trying to initialize an observable array from a json object which is rendered from the server as Javascript/Json;

Basically I have a simple model (from the server) that looks like this

    var BaseModel = { "changeRequestLocations": 
             [{ "location": "New Zealand", "devices": 
                      [
                        { "id": "5", "deviceName": "Server 1" },  
                        { "id": "6", "deviceName": "Server 2" }
                      ],
              "id": 1 }] };

I then initialize an observable array from the baseModel

    this.changeRequestLocations = ko.observableArray(BaseModel.changeRequestLocations);

This basically does what I want but the "devices" element is an array not an observable array.

I really need to have it as an observable array - is there a way to tell Knockout to do this automatically or do I need to do it manually?

See a fiddle here that shows the case

1 Answer 1

1

In itself Knockout does not do this for you automatically, so

  • you do it manually like your jsfiddle
  • you use the Knockout.Mapping plugin which is designed for this scenario: convert plain JavaScript objects to objects with observable properties.

So in your example you just need to write:

this.changeRequestLocations = ko.mapping.fromJS(BaseModel.changeRequestLocations);

and the mapping plugin will convert your location array into an observable array.

Demo JSFiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.