Kevin Dias
Kevin Dias

Reputation: 1076

How do i bypass the random id in array that firebase gives on response?

this is my console.log but i can only access the name not the messages, im able to print the name but when i try to print the messages i get [object][object] on the page when i print the data, want to remove the -LCE-36m4sdrPGFpusM6:

//output

messages:
 -LCE-36m4sdrPGFpusM6:
 date:"2018/5/11"
 haveConsultant:true
 hour:"12:40"
 message:"hi"
name:"Teste chat 2"

My code to print this output with angular coming from firebase , how can i do to access the message nested array???

getUsersChat() {

    let clientsKeys: Array < any > ;

    let i = 0;
    console.log('obter chats ativados');
    this.mySegService.getChats().take(1).subscribe(res => {

      clientsKeys = Object.keys(res);
      this.totalNumberClients += clientsKeys.length;
      clientsKeys.forEach(clientKey => {
        if (i < ++i && res[clientKey]['messages'] !== undefined) {
          this.clientsShortList.push({
            name: res[clientKey]['name'],
            messages: res[clientKey]['messages']
          });
        }
        i += 1;
      });

    console.log(this.clientsShortList);
   });

  }

// my html code

<mat-list>
  <mat-list-item *ngFor="let chat of clientsShortList">
    <mat-icon mat-list-icon>account_circle</mat-icon>
    <h4 mat-line>{{chat.name}}</h4>
    <button mat-button>see more</button>
  </mat-list-item>
</mat-list>

Upvotes: 1

Views: 135

Answers (2)

Saksham Gupta
Saksham Gupta

Reputation: 628

You can first get the random id using Object.keys like this:

var key = Object.keys(res[clientKey]['messages'])[0];

And then get the message object like this:

console.log(res[clientKey]['messages'][key])

Upvotes: 1

casieber
casieber

Reputation: 7542

A possible simple solution to this problem would be to JSON.stringify the messages object before attempting to console.log it.

Depending on the browser and format of the object, just calling console.log(obj) won't always do the trick.

In your case this would be a change to the line:

messages: res[clientKey]['messages']

to instead be

messages: JSON.stringify(res[clientKey]['messages'])

Upvotes: 1

Related Questions