cancel
Showing results for 
Search instead for 
Did you mean: 

How to show only unique values from a json file into combo box .. if there are multiple records containing the same name

Former Member
0 Kudos

How to show only unique values from a json file into combo box .. if there are multiple records containing the same name..

In my example: I have created a combo box shows list of countries ..data binded from json file..

Suppose the country name gets repeated in more than 1 record. How to not add repeated (same) name twice on combo box ?

below you can find the code i have used:

js.view

var page1 = new sap.m.Page("p1",{});

var oModel = new sap.ui.model.json.JSONModel({});

  oModel.loadData("Item/data.json");

  var page1 = new sap.m.Page("p1",{title:"Main Page"});

  var label1 = new sap.ui.commons.Label("l1",{text:"Country});

  var cBox1 = new sap.ui.commons.ComboBox("cb1",{

  value:"{/data}"

  });

  label1.setLabelFor(cBox1);

  var listitem1 = new sap.ui.core.ListItem().bindProperty("text","Country");

  cBox1.bindAggregation("items","/data",listitem1);

  cBox1.setModel(oModel);

  cBox1.bindValue("/selection");

  page1.addContent(cBox1);

json file

{

  "selection": "",

   "data": [

                  {

                  "Country":"India",

                  "Type": "[All]",

                  },

                 

                  {

                  "Country": "USA",

                  "Type":"[all]",

                   }

             ]

}

Suppose if i include another record in json file

{

  "Country":"USA",

   "Type": "[All]",

}

USA should not been shown on combo box.. because it is alrready present.

Please help me regarding this as i'm new to UI 5.. Thanks in advance..

View Entire Topic

Hi Abhi,

Here is the solution for your issue JS Bin Lin.

As others suggested there is no option yet available in UI5 but we can filter unique values using JavaScript.

Former Member
0 Kudos

It worked just perfect !!!

Former Member
0 Kudos

var country = sap.ui.getCore().getModel().getProperty("/data");

  for(var i=0; i<country.length; i++) {

   if(a.indexOf(country[i].Country) === -1) {

     a.push(country[i].Country);

   }

  }

why in "if" condition.. it is equal to -1.. what it means

junwu
Active Contributor
0 Kudos

-1 means it is not in the array

0 Kudos

It will search array a for the value country[i].Country. If it's not found then it will return -1. If the value is not already present in the array then only we will push that value to array. So that we can get unique values in array.

Hope you understood..

Former Member
0 Kudos

Yeah I understood it.. thanks for the explanation

Former Member
0 Kudos

Got a bit confused vivek.. what the array b[] does and can you explain the part after array b[] loop?

it would be helpful

0 Kudos

b holds the array of object. That object will have the unique country names. Use console.log(b) to get more information.