Reputation: 848
I have a IndustryData
observable array which will store data in the following format:
ID Name IsMapped
1 Name1 0
2 Name2 1
3 Name3 0
4 Name4 1
I am using the below mentioned select
to bind the data:
<select class="form-control" data-bind="options: $root.IndustryData, selectedOptions: $root.IndustryDataSelectedValues, optionsText: 'name', optionsValue: 'id'" multiple="multiple"></select>
IndustryDataSelectedValues
is an observable array which will store the selected values for the above select
and it will be initially empty. My requirement is that the row which is having IsMapped
value as 1 should be selected in my multi select
control and those items should be available in IndustryDataSelectedValues
observable array. In the above case Name2
and Name4
should be selected in my multi select
control and these two items should be available in IndustryDataSelectedValues
observable array.
How can I achieve this in knockout?
Upvotes: 0
Views: 792
Reputation: 139748
There are multiple ways to solve this:
IndustryDataSelectedValues
initialize
method on your viewmodel what you call when the data is ready in the IndustryData
So you need something like that:
initialize: function () {
this.IndustryDataSelectedValues(ko.utils.arrayMap(
ko.utils.arrayFilter(this.IndustryData, function (item) {
return item.IsMapped == 1
}), function (item) {
return item.id;
}));
}
Demo JSFiddle.
Where with the ko.utils.arrayFilter
you first select all the item where IsMapped == 1
then with the ko.utils.arrayMap
take the id
property of the previously found items and store these ids in the IndustryDataSelectedValues
Upvotes: 1