Controlling how an object is converted to JSON

http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.1.0.js"></script>
<ul data-bind="template: { name: 'peopleTmpl', foreach: ones}"></ul>
<hr/>
<div data-bind="text: ko.toJSON(ones, ['first', 'last'])"></div>
<hr/>
<ul data-bind="template: { name: 'peopleTmpl', foreach: twos}"></ul>
<hr/>
<div data-bind="text: ko.toJSON(twos, function(key, val) {
    return key ? val.first + ' ' + val.last : val;
})"></div>


<script id="peopleTmpl" type="text/html">
    <li>
        <input data-bind="value: first" />
        <input data-bind="value: last" />
        <span data-bind="text: full"></span>
    </li>
</script>

CSS

input { width: 75px; }

JavaScript

function PersonOne(first, last) {
    this.first = ko.observable(first);
    this.last = ko.observable(last);
    this.full = ko.dependentObservable(function() {
        return this.first() + " " + this.last();
    }, this);
}

function PersonTwo(first, last) {
    this.first = ko.observable(first);
    this.last = ko.observable(last);
    this.full = ko.dependentObservable(function() {
        return this.first() + " " + this.last();
    }, this);
}

var viewModel = {
    ones: [
        new PersonOne("John", "Smith"),
        new PersonOne("Sarah", "Smith"),
        new PersonOne("Ron", "Smith")
        ],
    twos: [
        new PersonTwo("Ted", "Johnson"),
        new PersonTwo("Jon", "Johnson"),
        new PersonTwo("Rachel", "Johnson")
        ]
};

ko.applyBindings(viewModel);