8

I'm trying to extract unique properties from a knockout.js observableArray of objects, to populate a drop menu. Being new to knockout, I'm really struggling with this!

I want to iterate over a contacts list, and populate a drop menu with a unique value from each person object within the observableArray. So in my code example below, I wish to populate my drop menu with a list of people 'type' - family, friend etc.

Looking on 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 HTML template

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

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

Joe
  • 127
  • 1
  • 2
  • 9
  • 1
    duplicate + better answer: http://stackoverflow.com/questions/14437849/knockout-arraygetdistinctvalues-of-objects – Dead.Rabit Sep 11 '14 at 15:19

1 Answers1

13

You cannot use such constructions self.contacts().type. You should get array of types first and then call 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();
});

Here is working fiddle: http://jsfiddle.net/VxT5Y/

Artem Vyshniakov
  • 16,355
  • 3
  • 43
  • 47