Knockout binding - select first filled object

2019-08-31 05:09发布

问题:

I have the following KnockoutJS code in order to make a databinding for a Addresses Form Editor where I can have 4 address types ("home", "office", etc).

http://jsfiddle.net/mxgFQ/1/

Right now everything is working great but the selectedAddress is being hardcoded to be the index 0

self.selectedAddress = ko.observable(self.addresses[0]);

Instead of doing this I want to selected the first address object that has data filled in.

Any clue on how to do this?

Appreciate.

回答1:

Knockout's utility function provides the very convienent arrayFirst function, which makes this simple:

self.selectedAddress = ko.observable(
        ko.utils.arrayFirst(self.addresses(), function(item) {
            return item.address1().length > 0;
        }));

Here is the updated fiddle.

Here is a handy reference for KO's utility functions: