0

I'm trying to display only unique values in a List. The values are loaded from the following JSON Model and I need to populate the List with all unique names:

{"Customers": [
{"name": "Customer A","age": "30"},
{"name": "Customer B","age": "25"},
...
]}

While searching for a possible solution i ran into the sap.m.ListBinding class and its function getDistinctValues(sPath) >> see API

This function should be returning an array of distinct values from a given relative Path. I've tried using the function in the following manner:

var oModel = this.getView().getModel("customers"),
oListBinding = new ListBinding(oModel, "customers>Customers", oModel.getContext("/Customers")),
arrValues = oListBinding.getDistinctValues("name");

But i keep getting arrValues=null. Any ideas to what I'm doing wrong here? I've also tried using customers>name, customers>/name and /name without any luck.

schnoedel
  • 3,918
  • 1
  • 13
  • 17
BlkJck
  • 3
  • 1
  • 4
  • have you tried `new ListBinding(oModel, "/Customers")`? Or `new ListBinding(oModel, "",oModel.getContext("/Customers"))` if you want to use a context? The ListBinding should have a Path that points to a array. – schnoedel Nov 15 '16 at 12:42

1 Answers1

0

Either if getDistinctValues() fails you, or if you need to measure distinctness across multiple attributes the technique below may be of use. Though this use case is for input box suggestions I provide it for the technique:

    handleSuggestClient: function(oEvent){
        var sValue = oEvent.getParameter("suggestValue");
        var filters = [];
        var uniqueNames = [];
        filters = [new sap.ui.model.Filter([
                new sap.ui.model.Filter("", function(oNode) { // blank first param passes in entire node to test function
                    var sVal = ((oNode.client + oNode.contact) || "").toUpperCase()
                    if (uniqueNames.indexOf(sVal) === -1){
                        uniqueNames.push(sVal);
                        return sVal.indexOf(sValue.toUpperCase()) > -1;
                    } else {
                        return false;
                    }
                })
        ], false)];
        this.oSFClient.getBinding("suggestionItems").filter(filters);
        this.oSFClient.suggest();
    },

The function within passed to the filter constructor includes logic to test for uniqueness and add matches to an array, etc.

If this is way off the topic let me know and I will delete the answer.

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67