简体   繁体   中英

Observable array from another JSON object with child arrays

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM