Konstantin Dinev
Konstantin Dinev

Reputation: 34905

Is it possible to create computed arrays with Knockout.js

I have a knockout.js ViewModel with an observable array:

function ItemsViewModel() {
    this.data = ko.observableArray([
        new Item(1, "One description"),
        new Item(2, "Two description"),
        new Item(3, "Three description"),
        // ... etc
    ]);
}

The Item looks like this:

function Item(id, name) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
};

Based on the observable array I have created in my ViewModel I would like to create a second computed array which would look like this:

function ItemsViewModel() {
    this.data = ko.observableArray([
        new Item(1, "One description"),
        new Item(2, "Two description"),
        new Item(3, "Three description"),
        // ... etc
    ]);

    this.computedData = // here I want to create a computed array based on the values
                        // of this.data
}

I cannot seem to find an example for how to create this computed array anywhere in the knockout.js documentation. Could you please give me an example of how to turn the first array into a computed array of the form:

this.computedData = [
    { dataItem: data[0].name + ' ' + data[0].id },
    { dataItem: data[1].name + ' ' + data[1].id },
    // ... etc.
]

Upvotes: 4

Views: 7725

Answers (1)

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

You can use computed observable for this:

self.computedData = ko.computed(function() {
    return ko.utils.arrayMap(self.data(), function(item) {
        return { dataItem: item.name() + ' ' + item.id() };
    });
});

Here is working example: http://jsfiddle.net/vyshniakov/3fesA/1/

Read more about computed in documentation: http://knockoutjs.com/documentation/computedObservables.html

Upvotes: 11

Related Questions