Access data from array of objects

Here is my TS file code:

 import { Component } from '@angular/core';
 import { NavController, NavParams } from 'ionic-angular';


  selector: 'page-showall',

templateUrl: 'showall.html'


export class ShowallPage {

constructor(public navCtrl: NavController, public navParams: NavParams) {
this.datas0 = [
    { number: "1", code: "apple0" },
    { number: "2", code: "orange0" },
    { number: "3", code: "banana0" },
    { number: "50", code: "lemon0" }

  this.datas1 = [
    { number: "1", code: "apple1" },
    { number: "2", code: "orange1" },
    { number: "3", code: "banana1" },
    { number: "50", code: "lemon1" }

  this.datas2 = [
    { number: "1", code: "apple2" },
    { number: "2", code: "orange2" },
    { number: "3", code: "banana2" },
    { number: "50", code: "lemon2" }

  this.datasCollection = [];
  this.datasCollection.push(this.datas0, this.datas1, this.datas2);
  this.mydata = this.datasCollection[Math.floor((Math.random() * this.datasCollection.length) + 0)];


mydata: any ;

datas0: Array<Object>;

datas1: Array<Object>;

 datas2: Array<Object>;

datasCollection: Array<Object>;


I am trying to access the data values from ‘mydata’ in html

Here is my HTML content

      <div class="row" *ngFor="let data of mydata">
        <div class="col">{{data.number}}</div>
        <div class="col">{{data.code}}</div>          

When i tried to print the ‘mydata’ variable, i got the following :


Currently i am getting the following error when the pages is loaded

Error in ./ShowallPage class ShowallPage - inline template:32:16 caused by: Cannot read property ‘code’ of undefined

JavaScript array indexes start at 0, so you have a fencepost bug in your random choice. Drop the “+1”.

That I know, and I had corrected it, but Actually my problem is how to access data values from an array of objects?

I don’t see that you have any further problem. Once I fixed that off-by-one, your code seemed to work fine for me.

I had fixed that,

this.mydata = this.datasCollection[Math.floor((Math.random() * this.datasCollection.length) + 0)];

as u can see the screenshot, I am getting data values when printing in console.

I need to acces the data from array of objects.

still I am getting the error
Error in ./ShowallPage class ShowallPage - inline template:32:16 caused by: Cannot read property ‘code’ of undefined

You have oversimplified your example here, then. I pasted it directly into a sample project, fixed the off-by-one bug, and it works fine.

Is it possible that you’re not actually initializing the array in the constructor as you describe here, but are instead doing it from storage or a network request or some other asynchronous event?

You don’t think the page is rendering too quickly on his machine? I believe you that it works. But just on principIe I would put this.mydata = new Array<Object>() in the constructor, and put the “real” definition in ngOnInit(). Maybe I’m paranoid, but I don’t put any actual computation in constructors anymore.

Also, I wouldn’t actually use Array<Object>(). I’d strongly type the whole file. But that’s a different conversation.

Not quite sure what you mean here, but this sounds like the sort of thing that qualifies as a race condition. Those are tough to diagnose and debug, which is why:

I don’t put any actual computation in constructors

I do, although in practice there may not be much difference between doing it there and in ngOnInit. I wholeheartedly agree with your other points regarding initialization (although I do it inline instead of in constructors) and strong typing.

hi, actually my problem is that i am getting the datas while printing in console, but not in html
I need to access data from an array of objects

i tried to implement the same using another code but also the same problem
see this

 this.locations = ['../assets/1.json', '../assets/2.json','../assets/3.json'];
 this.randomJsonFile = this.locations[Math.floor((Math.random() * this.locations.length) + 0	)];
 this.http.get(this.randomJsonFile).map(res => res.json())
 .subscribe(data =>{
  this.ShowcasedAttractions = data;
   // this.results = data;
   // console.log(this.results);

Exactly as I said, you are actually getting the data from an asynchronous request. Initialize the array in the constructor to a sane dummy value.

can u pls tell me how to initialize array in constructor to same dummy value, i am new to ionic and TS

Come on, you did it in the code you originally posted.

but actually ‘mydata’ variable is not declared as array
its declared as mydata: any ;

actually my problem is that i am getting the datas while printing in console, but not in html

Your machine is trying to build the DOM before your array is defined. When you log to the console later, it is after your array is defined. So you need to define the array before the DOM is rendered. Do that in the constructor. After your array is defined, you can populate it with values however you want.

how can i do that? I am new to this
can u pls tell how to define array before DOM is created

Put your initialization statements at the beginning of the constructor – the lines like = new Bar();

Make sure that every variable you refer to in your template is defined like that in the constructor. Only after all variables are defined, start doing computation. This is especially important when your computation is inherently asynchronous, like an Observable subscription, a Promise or a callback.

By the way, there are a lot of stylistic problems with your code. My suggestion would be that you spend some time with tutorials on TypeScript and Angular 2 before continuing to program in Ionic. Things that seem impossible right now will become obvious.

i have initialized the datas0,datas1 etc at the very first line of the constructor itself
can u pls write a sample code

I don’t believe that, because the code in your initial post (which does in fact initialize things as you describe) works.

I Just wanted to add this here, this thread was one of the dozen tabs i had open when troubleshooting a similar problem.

So I’ve compiled some notes in an answer over on Stack Exchange that might help others