1

I want to loop through an array of objects. but I could not do the loop to "purchases". This is the result that I have by console:

[{
  "createdAt": "Fri Aug 31 2018 15:19:03 GMT-0400 
    (Eastern Daylight Time)
  ", 
  "customer": {
    "address": "test",
    "lastname": "Carrio",
    "name": "Mabel",
    "phone": "786222222"
  },
  "purchases": {
    "0": {
      "product": {
        "categoryS": "-L9QdqynslyGy8Ft1G9z",
        "location": "en tienda",
        "name": "Memoria",
        "price": 12
      },
      "quantity": 3
    }
  },
  "totalPrice": 36,
  "uid": "fr0Yix3T2hMio3KzwAB1r6aJbZA2",
  "$key": "-LLGQAB3V_PRiW2v02bx"
}]

component.ts

ngOnInit() {
  this.invoiceService.getInvoices().snapshotChanges().subscribe(data => {
      this.invoiceList = []

      data.forEach(element => {
          let x = element.payload.toJSON()
          this.invoiceList.push(x);
        }
      }
    }
  }
}

list.component.html

<tr *ngFor="let invoice of invoiceList">
  <td>{{invoice.customer.name}} {{invoice.customer.lastname}}</td>
  <td>{{invoice.totalPrice}}</td>
  <td>{{invoice.purchases.product.name}}</td>
  <--- Error 
</tr>

any idea?

3
  • Are you trying to convert the purchases element into array? Commented Sep 6, 2018 at 18:50
  • It would be nice if you refactor your Template code a bit as well. :) Commented Sep 6, 2018 at 18:53
  • with reference to your comment in the deleted answer ... ngFor only supports binding to iterables such as arrays ... not true ... see angular.io/api/common/KeyValuePipe introduced in ng6.1 ... but true if you are strictly referring to v5 Commented Sep 6, 2018 at 19:33

2 Answers 2

2

Your component code needs refactoring. Here's how you can refactor it:

// First
import 'rxjs/add/operator/map';

// Then
ngOnInit() {
  this.invoiceService.getInvoices().snapshotChanges()
    .map(data => data.map(datum => datum.payload.toJSON()))
    .map(data => {
      return data.map(datum => {
        let purchases = [];
        for (let key in datum.purchases) {
          purchases.push(datum.purchases[key]);
        }
        datum.purchases = purchases;
        return datum;
      });
    })
    .subscribe(data => this.invoiceList = data);
}

Also, since doing something along the lines of Object.0 will throw an error, you should be using the Array member access pattern. Your template will have something like:

<tr *ngFor="let invoice of invoiceList">
  <td>{{invoice.customer.name}} {{invoice.customer.lastname}}</td>
  <td>{{invoice.totalPrice}}</td>
  <td>{{invoice.uid}}</td>
  <td>{{invoice.createdAt}}</td>
  <td>
    <li class="list-group-item" *ngFor="let purchase of invoice.purchases">
      {{purchase.product.name}}
    </li>
  </td>
  <td>
    <a class="btn btn-danger text-white" (click)="onDelete(invoice.$key)">
      <i class="fas fa-trash-alt"></i>
    </a>
  </td>
</tr>

Here's the Updated StackBlitz.

Sign up to request clarification or add additional context in comments.

9 Comments

in this case it only returns the value that is in position 0, and there may be more than one
Why isn't purchases an array in that case? Would it be possible to get the purchases as an array instead of an object with keys as 0, 1, 2...? If yes, make that an array.
because "purchases" has in addition to "products", has "quantity"
Check the updated answer if that helps. Will you be looping through all the purchases in the td elements?
Error: Cannot find a differ supporting object '[object Object]' of type 'object'.
|
1

Have Modified your code little bit.

<tr *ngFor="let invoice of invoiceList">
<td>{{invoice.customer.name}} {{invoice.customer.lastname}}</td>
<td>{{invoice.totalPrice}}</td>
<td>{{invoice.purchases["0"].product.name}}</td> //Changes are here

If key of an Object is a number, you have to access it like [0] or ["0"]

Hope That Helped!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.