Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
]
like image 443
Konstantin Dinev Avatar asked Dec 21 '22 12:12

Konstantin Dinev


1 Answers

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

like image 181
Artem Vyshniakov Avatar answered Jan 05 '23 16:01

Artem Vyshniakov