Since you're trying to dynamically access properties and/or subproperties of your objects, you'll need to use eval
instead of dynamic property access. Thus x[sortField]
will need to be eval('x.' + sortField)
.
Also because the properties are observables, you'll need to add trailing parentheses too: eval('x.' + sortField)()
.
Here is your updated sort function (with some other optimizations):
arrResponses.sort(function (x, y) {
var xLess = eval('x.' + sortField + '() < y.' + sortField + '()');
if (descending) {
return xLess ? 1 : -1;
} else {
return xLess ? -1 : 1;
}
});
Another solution, one that I'd recommend more strongly, is to use computed observables in your objects to encapsulate the displayed data. Thus your Response
object would contain the following:
this.crisisType = ko.computed(function () {
return this.eventRelatesCrisisTypes()[0].crisisType().name();
}, this);
this.countryRegion = ko.computed(function () {
return this.country().name() + ', ' + this.country().region().name();
}, this);
Now you could bind to these computed observables in your view and use them in your sort function without having to use eval
.