1) self.RecipientOptions.SelectedGenders(allData.RecipientOptions.SelectedGenders);
2) for (var i = 0; i < allData.RecipientOptions.SelectedGenders.length; i++) {
var chkboxitem = new CheckboxOption(allData.RecipientOptions.SelectedGenders[i].Display, allData.RecipientOptions.SelectedGenders[i].Value);
self.RecipientOptions.SelectedGenders.push(chkboxitem);
}
3) var mappedSelectedGenders = $.map(allData.RecipientOptions.SelectedGenders, function (item) { return new CheckboxOption(item.Display, item.Value); });
self.RecipientOptions.SelectedGenders(mappedSelectedGenders);
<!--ko foreach: Lists.GenderCodes()-->
<div class="fieldControl" style="margin-left:30px">
<input type="checkbox" data-bind="checkedValue : $data, enable: !$root.RecipientOptions.AllGenders(), checked:$root.RecipientOptions.SelectedGenders"/><span data-bind=" text: Display"></span>
</div>
<!-- /ko-->
<div style="clear:both"></div>
<div data-bind="foreach: RecipientOptions.SelectedGenders()">
<span data-bind="text: $data.Display"></span>, <span data-bind=" text: $data.Value"></span>
</div>
/////////////Displaying what's in the array below, checkboxes not checked.///////
<script src="@Url.Content("~/Scripts/TestViewModel.js")" type="text/javascript"></script>
<h2>Test</h2>
<!--ko foreach: GenderList()-->
<div class="fieldControl" style="margin-left:30px">
<input type="checkbox" data-bind="checkedValue : $data, checked: $root.SelectedGenders"/><span data-bind=" text: Display"></span>
</div>
<!-- /ko-->
<br /><br />
<div style="clear:both"></div>
<div data-bind="foreach: SelectedGenders()">
<span data-bind="text: $data.Display"></span>, <span data-bind="text: $data.Value"></span>
</div>
<script type="text/javascript">
$(document).ready(function () {
//binding has to occur after html is rendered
ko.applyBindings(new TestViewModel());
}); //end document ready
</script>
function CheckboxOption(display, value) {
this.Display = display;
this.Value = value;
}
function TestViewModel() {
var self = this;
self.GenderList = ko.observableArray();
self.SelectedGenders = ko.observableArray();
self.GenderList.push(new CheckboxOption("Male","M"));
self.GenderList.push(new CheckboxOption("Female","F"));
self.GenderList.push(new CheckboxOption("Unknown", "U"));
self.SelectedGenders.push(new CheckboxOption("Female", "F"));
}
for (var i = 0; i < dataFromServer.SelectedGenders.length; i++) {
var chkboxitem = new CheckboxOption(dataFromServer.SelectedGenders[i].Display, dataFromServer.SelectedGenders[i].Value);
var matchingGender = ko.utils.arrayFirst(self.GenderList(), function (gender) {
return dataFromServer.SelectedGenders[i].Value === gender.Value;
});
self.SelectedGenders.push(matchingGender);
}