javarebel javarebel - 3 months ago 39
Javascript Question

Knockout Mapping toJSON - cannot ignore nested child

Assume I have a viewModel like below.

var data = {
a: { a1: "a1", a2: "a2" },
b: "b"
};


I would like to ignore a.a1 and b. So my expected JSON is

{"a":{a2:"a2"}}


However, on doing this

var result = ko.mapping.toJSON(data, { ignore: ["a.a1", "b"] })


I am getting result=

{"a":{"a1":"a1","a2":"a2"}}


Knockout mapping is not ignoring a.a1. Is this a bug in the plugin? It correctly ignored 'b' but why not 'a.a1'?

Answer

The names found in the ignore array should be the name of the property, regardless of what level it is in the object. You have to use:

{ ignore: [ "a1", "b" ] }