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 ?

1

2 Answers 2

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;
});
Sign up to request clarification or add additional context in comments.

3 Comments

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.
This doesn't actually delete them just creates a json payload and then removes unnecessary properties from that payload only
I used Your solution in my code but the item is not getting deleted and here is jsfiddle : 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?
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.

1 Comment

I used Your solution in my code but the item is not getting deleted and here is jsfiddle : 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.