0

I am trying to see if I can assign a JavaScript variable to the value of a value of a KO Observable.

The reason for this is I want to assign it to a jquery module, as a property.

I know I can do:

 var viewModel = { firstName : ko.observable("Bert"), lastName : ko.observable("Smith"), pets : ko.observableArray(["Cat", "Dog", "Fish"]), type : "Customer" }; viewModel.hasALotOfPets = ko.computed(function() { return this.pets().length > 2 }, viewModel) var jsonData = ko.toJSON(viewModel); 

But, what if I don't want everything that is in the view model? Can i just only select n number of items?

3
  • Which items do you want to omit? Are there sufficiently few that you could exclude them manually? Commented May 31, 2013 at 20:09
  • Not necessarily. This was just an example that I provide. But for example, I would want to only get like firstName and type. I just want to know if I can only get select values. Commented May 31, 2013 at 20:22
  • You may be able to do something with the knockout mapping plugin, but I'm not sure of the syntax off the top of my head Commented Jun 1, 2013 at 13:44

1 Answer 1

1

There two concepts here:

  1. Retrieving the object from a Knockout observable
  2. Manipulating a JavaScript array

Code:

var start = 1; // index of Dog var n = 1; // just one item var jsonData = ko.toJSON(viewModel.pets().slice(start, start + n)); 

In Knockout, observables are functions. To set its value you call it with a parameter. To get its value, you call it.

JavaScript arrays have a slice function that can be used to get a smaller array.

UPDATE based on comments on the question:

If you want to take n fields from viewModel, ko.toJSON will work on a subsetted view model:

var n = 2; var count = 0; var subModel = {}; for (var k in viewModel) { if (count >= n) break; if (viewModel.hasOwnProperty(k)) { subModel[k] = viewModel[k]; count++; } } var jsonData = ko.toJSON(subModel); 

If you want specific fields only, create a subsetted model with those:

var jsonData = ko.toJSON({ firstName: viewModel.firstName, type: viewModel.type }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.