1

I have been stuck trying to integrate a json response to a ion-option tag. this is my html code:

<ion-item>
          <ion-label>Country</ion-label>
                  <ion-select formControlName="country">
                    <ion-option *ngFor="let value of values">{{value}}</ion-option>
                  </ion-select>
                </ion-item>

my values json object look like this:

values = {4: "Afghanistan", 8: "Albania", 10: "Antarctica", 12: "Algeria"};


This is defined in the related class of the above html file.

I get the following error:


ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Please can someone tell me what I am doing wrong? Is the format of JSON object not supported?

Thanks in advance!

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • here demo link : https://stackblitz.com/edit/ionic-fhpjje?file=pages%2Fhome%2Fhome.html – Chandru Nov 27 '17 at 13:54
  • 1
    Possible duplicate of [Angular 2 - iterating over json array inside a json object](https://stackoverflow.com/questions/36162594/angular-2-iterating-over-json-array-inside-a-json-object) – Jota.Toledo Nov 27 '17 at 14:09

3 Answers3

1

Your values is an object it should be an array as follows,

values = [{"Afghanistan", "Albania","Antarctica", "Algeria"}]; 

you can convert the object to array as follows,

var obj = {4: "Afghanistan", 8: "Albania", 10: "Antarctica", 12: "Algeria"}; 
var result = Object.keys(obj).map(function(key) {
  return  obj[key];
});

console.log(result);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Slightly different from @Sajeetharan's answer. It's enough if your data is within an array, since JSON is directly not iterable over ngFor

values = {
            data: [
                {id: "4", value: "Afghanistan"},
                {id: "8", value: "Albania"},
                {id: "10", value: "Antarctica"},
                {id: "12", value: "Algeria"},
            ]
        };

and then you could do

<ion-option *ngFor="let val of values.data">{{val.id}}----{{val.value}}</ion-option>
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
0

Hi I actually used a function provided in one of the answers: Angular 2 - iterating over json array inside a json object answer by: Ankit Singh

he has mentioned the use of a function:

generateArray(obj){
   return Object.keys(obj).map((key)=>{ return obj[key]});
}

which converts my json object into an array!