Knockout serialization with ko.toJSON - how to ignore properties that are null

前端 未结 2 2139
春和景丽
春和景丽 2020-12-10 11:50

When using:

var dataToSave = ko.toJSON(myViewModel);

.. is it possible to not serialize values that are null?

Seri

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 12:14

    You can add a toJSON method to your view model and use that to remove all the unneeded properties:

     ViewModel.prototype.toJSON = function() {
         var copy = ko.toJS(this);
         // remove any unneeded properties
         if (copy.unneedProperty == null) {
             delete copy.unneedProperty;
         }
         return copy;
     }
    

    You could probably automate it to run through all your properties and delete the null ones.

提交回复
热议问题