1

I am new to the knockoutjs, I have following viewmodel:

var Testing = function(){

   this.Username = ko.observable("");  
   this.Password = ko.observable("");  
   this.email = ko.observable("");

}

I need to convert only certain data bind values(Username and password) into json. All the values are getting converted into json when I use like this data = ko.toJSON(this);

So how I can filter certain data bind values and convert into json ?

GôTô
  • 7,974
  • 3
  • 32
  • 43
Pavithra
  • 29
  • 5
  • Also check out this answer if you want to override the toJSON method [Knockout serialization with ko.toJSON - how to ignore properties that are null](http://stackoverflow.com/questions/12461037/knockout-serialization-with-ko-tojson-how-to-ignore-properties-that-are-null) – PW Kad Jun 24 '14 at 13:24

2 Answers2

2

You could either only serialize what you want or take Ryan Neidermeyer's approach and just remove the unwanted properties -

var items = ko.toJS(this);
var mappedItems = ko.utils.arrayMap(items, function(item) {
    delete item.email;
    return item;
});
PW Kad
  • 14,953
  • 7
  • 49
  • 82
  • Thank you for the solution.I don't want to delete any of them,i need to select certain values and converted into JSon while sending into server. – Pavithra Jun 25 '14 at 09:21
  • This doesn't actually delete them just creates a json payload and then removes unnecessary properties from that payload only – PW Kad Jun 25 '14 at 11:57
  • I used Your solution in my code but the item is not getting deleted and here is jsfiddle : http://jsfiddle.net/PavithraHM/4FGXB/5/ when i gave alert before mappedarray its getting converted into Javascript object, and the item is not getting loaded.Once i delete the items i need to convert rest of things to json. where i can find this kind of methods in the knockoutjs Document? – Pavithra Jun 26 '14 at 11:48
1

You can add a toJSON method to your ViewModel and do what ever filtering you need there:

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

Take a look at the docs for more information about serializing to JSON.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • I used Your solution in my code but the item is not getting deleted and here is jsfiddle : http://jsfiddle.net/PavithraHM/4FGXB/6/ ,Once i delete the items i need to convert rest of things to json. where i can find this kind of methods in the knockoutjs Document? – Pavithra Jun 27 '14 at 06:07