Access data from array of objects


#1

Here is my TS file code:

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

@Component({

  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)];
  console.log(this.mydata);


}


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>          
    </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


#2

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


#3

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


#4

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.


#5

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


#6

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?


#7

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.


#8

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.


#9

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

 getRemoteData(){
 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;
   console.log(this.ShowcasedAttractions);
   // this.results = data;
   // console.log(this.results);
  });
}

#10

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.


#11

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


#12

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


#13

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


#14

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.


#15

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


#16

Put your initialization statements at the beginning of the constructor – the lines like this.foo = 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.


#17

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


#18

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


#19

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