简体   繁体   中英

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'?

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" ] }

I had similar ignore list where some "ids" have to be suppressed and others left as is. I wanted to expand on the answer so that people using fromJS can see specific ignores do work

var data1 = {
        invoice: { id: 'a1', name: 'a2', type: 'a3'},
        shipping: "b1",
        id:"c1"
};

var resultvm = ko.mapping. fromJS (data1, {'ignore':["invoice.id", "ship"]}); ko.applyBindings(resultvm);

Will give you an output as below. Notice that only the id for invoice has been ignored.

{"invoice":{"name":"a2","type":"a3"},"id":"c1"}

But toJSON gives

Code:

var result = ko.mapping. toJSON (data1, { ignore: ["invoice.id", "shipping"] });

Result:

{"invoice":{"id":"a1","name":"a2","type":"a3"},"id":"c1"}

Here is my jsFiddle: https://jsfiddle.net/3b17r0ys/8/

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