1

Working away on a Ionic-PouchDB - I'm new to both - and pretty basic at JS.

I have a service that returns data from PouchDB and an ngfor loop that populates the view. It works fine

From the page typescript

ngOnInit() {
    this.slates = this.api.getSlates();
    }

From the HTML

 <ion-content>
  <ion-list>
    <ion-item button detail lines="inset" *ngFor="let slate of slates" (click)="openDetails(slate)">
  {{ slate.createdon | date:'EEE  - d - LLL hh:mm a yyyy' }} --- {{ slate._id }}
</ion-item>
</ion-list>
</ion-content>

If I console.log this.slates I get enter image description here So far so good

I need to find out how many objects there are in the what look like an array - in this case 10. Also need to be able to get hold of data in each element. e.g. the _id or type from the objects

enter image description here

If I do say

ngOnInit() {
    this.slates = this.api.getSlates();
    console.log(this.slates);
    console.log(Object.keys(this.slates));
}

I just get an empty array.

Any help much appreciated - it'll help my sanity.

Townheadbluesboy
  • 265
  • 2
  • 4
  • 16
  • Duplicate for the first part: https://stackoverflow.com/questions/28811911/find-array-length-in-javascript Traversing JSON seems like another question (which also likely has a duplicate). This isn't an Ionic question. – isherwood Oct 02 '19 at 14:48

2 Answers2

2

To get the length of the array, use

this.slates.length

Object.keys(this.slates) returns the keys from the key-value pairs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45
1

For the first part you can use

const numberOfSlates = this.slates.length;

For the second one you can use find() to get the first result:

const targetId = "slate:1546427619624:cameraa:x:5";
const foundItem = this.slates.find((slate) => slate["_id"] === targetId);

Update - why is length = 0?

Based on your comments your seeing a zero length when checking right after.

You are correct, this is because the operation is async so its not populated straight away.

Without seeing the code for your .getSlates() this is just a guess but if it returns a promise then you can do:

ngOnInit() {
    this.api.getSlates().then((res) => {
       this.slates = res;
       console.log(this.slates);
       console.log(this.slates.length);
    });
}
rtpHarry
  • 13,019
  • 4
  • 43
  • 64
  • Thanks rtpHarry `const numberOfSlates = this.slates.length; ` used as ` console.log("Number of slates -- " + numberOfSlates);` gave me `Number of slates -- 0` Is it because the call to PouchDB at the beginning is returning a promise which I am pushing onto an array before returning it to the `this.slates = this.api.getSlates();` ? and this is all being run within ngOnInit ? – Townheadbluesboy Oct 03 '19 at 08:02