Unique objects from the observed object properties of the object

I am trying to extract unique properties from a knockout.js observableArray object to populate a drag and drop menu. Being new to knockout, I really struggle with this!

I want to iterate over the contact list and populate the transition menu with a unique value from each person object in the observed array. So in my code example below, I want to populate my menu with a drag and drop list of people like "family", "Friend", etc.

Looking at Google, I found a similar function, but it does not return any values, even if I console.log the results?

//dummy data more rows in actual code... var people = [ { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: " anemail@me.com ", type: "family" }, { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: " anemail@me.com ", type: "friend" } ]; function ContactsViewModel(people) { var self = this; self.contacts = ko.observableArray(people); self.uniqueSelect = ko.dependentObservable(function() { return( ko.utils.arrayGetDistinctValues(self.contacts().type).sort()); }, self); }; ko.applyBindings(new ContactsViewModel(people)); 

And the HTML template

 <p>Show me: <select data-bind="options: ContactsViewModel.uniqueSelect"></select></p> 

Any help is appreciated, as a noob I'm lost! Thanks

+7
source share
1 answer

You cannot use such self.contacts().type constructs. You must first get an array of types, and then call the Distinct function:

 self.uniqueSelect = ko.dependentObservable(function() { var types = ko.utils.arrayMap(self.contacts(), function(item){ return item.type}) return ko.utils.arrayGetDistinctValues(types).sort(); }); 

The fiddle works here: http://jsfiddle.net/VxT5Y/

+11
source

All Articles