Reputation: 839
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.
Upvotes: 2
Views: 1001
Reputation: 2177
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
}
Upvotes: 4