简体   繁体   中英

Array of JSON Objects to Knockout Observable Array With Observable Properties

My app has an ajax call that will return an array of JSON objects.

[
{"ID":2,"Name":"Name 1","CreatedOn":"/Date(1432892160000)/"},
{"ID":7,"Name":"Name 2","CreatedOn":"/Date(1432892160000)/"},
{"ID":8,"Name":"Name 3","CreatedOn":"/Date(1432892160000)/"},
{"ID":9,"Name":"Name 4","CreatedOn":"/Date(1432892160000)/"},
{"ID":10,"Name":"Name 5","CreatedOn":"/Date(1432854000000)/"}
]

I need to then assign these to a knockout observable array where the object properties are also observable.

I can create the observable array without a problem.

viewModel.newArray= ko.observableArray([]);
viewModel.newArray(result.ReturnedObjects);

However I can't suss out how to push to the observable array and make the properties of each object observable.

Use Knockout Mapping Plugin . Something like this should work

function vm(result){
  var self = this;
  self.items = ko.observableArray();
  ko.mapping.fromJS(result.ReturnedObjects,{},self.items)
  console.log(self.items()); //array with each object props as observables
}

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