Knockout does not display object properties in array

It seems that the knockout does not correctly display the properties of the objects in the array.

See this example from the Chrome console:

> var viewmodel = ko.mapping.fromJS({list:[]}); undefined > viewmodel.list().unshift({ name : ko.observable("Foo") }); 1 > viewmodel.list()[0].name(); "Foo" > var js = ko.mapping.toJS(viewmodel); undefined > js.list[0].name; undefined 

So, the javascript object is created, but the 'name' property is not displayed.

Any ideas are very welcome!

+6
source share
2 answers

From http://knockoutjs.com/documentation/plugins-mapping.html , about the toJS() function:

This will create an unselected object containing only the properties of the mapped object that were part of your original JS object.

Since the "name" was not part of the original object that you matched, it does not get unmapped. You must tell the mapping plugin to enable this particular property:

 var js = ko.mapping.toJS(viewmodel, { include: ['name'] }); 
+11
source

Although Niko's answer is correct, there is a way to overcome this problem.

I have to say that this is a bit ugly hack, but it does the job, and it is pretty easy to understand:

 ko.mapping.toJS(ko.mapping.fromJSON(ko.toJSON(viewmodel))) 

I map the view model from observable to json to observable (with all displayed properties) object.

+3
source

Source: https://habr.com/ru/post/913323/


All Articles