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!

2

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

4 Comments

Hi thanks for the quick response! but actually I'm receiving the above format through an api. I can't change it. Can you provide another solution?
Thanks it did the trick! but won't I be able to use the related ids?
you can still use ids
I actually upvoted it. no idea who downvoted. Thanks!
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!

Comments

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>

2 Comments

any idea how I could use the ids in the json to this list?
Yes, Why not check updated answer, but slight modification in your response is required.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.