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

前端 未结 2 2096
春和景丽
春和景丽 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:07

    Remember that ko.toJSON is just a modification of JSON stringify. You can pass in a replacer function.

    As an example of using a replacer function in Knockout, I put together a JSFiddle based on one of the knockout tutorials. Notice the difference between the makeJson and makeCleanJson functions. We can choose not to return any values in our replacer function and the item will be skipped in the JSON string.

    self.makeJson = function() {
        self.JsonInfo(ko.toJSON(self.availableMeals));
    };
    
    self.makeCleanJson = function() {
        self.JsonInfo(ko.toJSON(self.availableMeals, function(key, value) {
            if (value == null)
            {
                return;
            }
            else
            {
                return value;
            }
        }));
    };
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题