Search code examples
arraysjsonangulartypescriptngfor

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


I have a JSON:

json: string = `{
          "name" : "John",
          "surname" : "Walsh",
          "age" : "23"
    }`;

And I need to show it in table:

<table width="700">
            <caption>All Users</caption>
            <thead>
                <tr>
                    <th>name</th>
                    <th>surname</th>
                    <th>age</th>
                </tr>
            </thead>
            <tbody>
                 <tr>
                    <td *ngFor="let names of users"></td>
                       {{ names}}
                </tr>
            </tbody>
        </table>

I tried to do like this:

users = JSON.parse(this.json);

but got an error:

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

Then I tried convert users to array like this:

arr:Array<{key: string, value: string}> = [];
constructor(){
    for (var key in this.users) {
      if (this.users.hasOwnProperty(key)) {
       this.arr.push({ key: key, value: this.users[key] });
      }
 }
}

but I can't iterate it using NgFor.


Solution

  • In the first place, you need to correct array of your users to this:

    users = [{
          "name" : "John",
          "surname" : "Walsh",
          "age" : "23"
    },{
          "name" : "Mike",
          "surname" : "Mikic",
          "age" : "25"
    }];
    

    In the same time, you should iterate and create a new row each time you pass one object:

    <table width="700">
        <caption>All Users</caption>
        <thead>
            <tr>
                <th>name</th>
                <th>surname</th>
                <th>age</th>
            </tr>
        </thead>
        <tbody>
             <tr *ngFor="let user of users">
                <td>
                      {{user.name}}
                </td>
                <td>
                      {{user.surname}}
                </td>
                <td>
                      {{user.age}}
                </td>
            </tr>
        </tbody>
    </table>