Knockout is not mapping the properties of an object in an array
Asked Answered
D

2

7

It seems that knockout is not mapping the properties of objects in an array correctly.

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 being created, but the 'name' property does not get mapped.

Any ideas are very welcome!

Delinquent answered 16/4, 2012 at 13:29 Comment(0)
U
11

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

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

As "name" was not part of the original object you mapped, it does not get unmapped. You need to tell the mapping plugin to include this specific property:

var js = ko.mapping.toJS(viewmodel, { include: ['name'] });
Unwisdom answered 16/4, 2012 at 13:54 Comment(3)
Thanks for the quick answer. Is there any way of modifying the behaviour to map every property? The documentation doesn't seem to mention this.Delinquent
@RichardAstbury I don't think so. You will need to hard code this into a customized version of the mapping plugin.Unwisdom
I have since found ko.toJSON(viewModel) which seems to do the job.Delinquent
C
3

Although Niko's answer is correct - there is a way to overcome this issue..

I have to say it's a bit of an ugly hack but it does the job and it's 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 properties mapped) to object.

Countable answered 25/9, 2014 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.