Angular2 ngFor loop help

Question:

I have an nvi.json file that looks like this:

[
     {
    "abbrev": "gn",
    "book": "Gênesis",
    "chapters": [
      {
        "1": {
          "1": "...",
          "2": "..."
        }
      },
      {
        "2": {
          "1": "...",
          "2": "..."
        }
      },
      {
        "3": {
          "1": "...",
          "2": "..."
        }
      }
     ]
     }
    ]

And I'm accessing it like this:

export class BookPage {
    public chapters: Array<string>;
    private url: any = "../../assets/nvi.json";

    constructor(public navCtrl: NavController, private NavParams: NavParams, public http: Http) {
    let id = NavParams.get('id');

    this.http.get(this.url).map(res => res.json())
      .subscribe(data => {
        this.chapters = data[id].chapters[0];
        console.log(this.chapters);
      });
      }

this.chapters returns the first chapter where it contains the verses, but I am not able to loop these verses.

<div *ngFor="let item of chapters">
     {{item}}
    </div>

Console:

EXCEPTION: Error in ./BookPage class BookPage - inline template:33:5 caused by: Cannot find a differ supporting object '[object Object]' of type 'object'.      NgFor only supports binding to Iterables such as Arrays.

Answer:

From what I could simulate here your problem is in pure JavaScript, see json is an object or even if it looks like a nested array, it is not in this format.

See how to turn an object into an array:

var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });

in case the object you are exposing chapters at least should go through a process like this:

var arr = Object.keys(chapters[1]).map(function (key) { return chapters[1][key]; });

and one more thing it's no use defining the type of variable and then setting a value of a different type, which will prevail will be the last type set.

public chapters: Array<string>;
...
this.chapters = data[id].chapters[0];

By doing this chapters will become an object not an array. do a console.log(chapters); and look closely at this object in the console, with the real data it will be easier for you to see the behavior.

Hope this helps.

A hug.

Scroll to Top