Knockout binding - select first filled object

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).

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?



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:

Need Your Help

multi array in an array using foreach

php arrays loops foreach

I'm using foreach to echo array multidimensional array.

Why are visitors to my site following absolute links as if they're relative?

html logging hyperlink server

Every page on my website has a navbar with some absolute links, to pages like /archive and /atom.xml. These are present on pages like /post/post-title.