Is it possible to create computed arrays using Knockout.js

I have 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 is as follows:

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

Based on the observable array that I created in my ViewModel , I would like to create a second computed array that 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 find an example of how to create this computed array anywhere in the knockout.js documentation. Could you give 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. ] 
+4
source share
1 answer

You can use computed to observe:

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

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

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

+12
source

All Articles