Retrieve the document id along with the corresponding data from a collection

Retrieving data from the collection leads and displaying all documents in an HTML table. Upon clicking, I need to extract the document ID of the clicked item as it serves as the sole primary key.

P.S I am able to obtain records of all documents in an array format. However, I require the document ID to be included in this same array.

Below is the code snippet that I'm utilizing to retrieve the data. I am storing the information in the tableData array. I want the docID included within this array as well.

 this.firestore.collection('leads' , ref => ref 
.limit(5)
).snapshotChanges()
.subscribe(response => {
if(!response.length){
  console.log("no data available");
  return false;
}
this.firstInResponse = response[0].payload.doc;
this.lastInResponse = response[response.length - 1].payload.doc;


this.tableData = [];
for(let item of response){
  this.tableData.push(item.payload.doc.data()); 
  console.log(this.tableData);
}

...

Providing screenshots of console logs and Firestore for better understanding.

https://i.sstatic.net/2Mu93.png

Edit 1

After testing this approach

for(let item of response){
  var data = item;
  Object.assign(data, {id : item.payload.doc.id})
  this.tableData.push(data);
  console.log(this.tableData);

The actual structure of my array was disrupted, as illustrated in the screenshot below

https://i.sstatic.net/j8Wqs.png

Answer №1

Give this a shot:

for(const entry of response){
    const data = Object.assign(entry.payload.doc.data(), {id: entry.payload.doc.id});
    this.tableData.push(data);
    console.log(this.tableData);
}

I extracted the id from entry.payload.doc.id and then added it as a property to the data object before pushing it to the tableData array.

Hopefully, this clarifies things for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the functionality of observable in Angular? The 'includes' property is not present in the 'Observable' type

I am currently diving into the world of Angular5 and I have been using Firebase to fetch data for my page display. While researching how to retrieve data from Firebase using AngularFire, I found that many examples were outdated. Eventually, I learned that ...

Dynamic cell editing feature in PrimeNG table

Looking to implement the PrimeNG Table. https://i.stack.imgur.com/bQycr.png Check out the live demo on StackBlitz. The table has three editable columns. The "Property Name" column always displays a text box in edit mode, while the "Property Value Type" ...

What is the best way to generate a dynamic table row in Angular Material?

Could someone assist me with implementing expandable rows in my HTML table using Angular Material, similar to the example in this image: https://i.sstatic.net/QJtFX.png The concept is that when the content in a cell is too long, clicking on that cell will ...

Showing the unique identifier instead of the actual data in HTML for a Firebase Object using Angularfire

Currently, I am utilizing AngularFire for a specific project. The structure of my firebase Object is as follows: { mainKey: { key1:value1, key2:value2 }, mainkey2: { key3:value3 } } The data has been inputted in a manner tha ...

What is the syntax for typing a mongoose populated field in Typescript?

I am faced with a field that can either be an ID or have a value, and I am attempting to type this field using TypeScript import { InferSchemaType, Schema, Types, model } from 'mongoose'; const personSchema = new Schema({ _id: Schema.Types.Obj ...

Creating a CSS class in a separate file for an element in Angular 4

Looking for some help with my code setup. Here's what I have: <div class="over"> Content </div> In my component file, this is what it looks like: @Component({ selector: 'app', templateUrl: './app.componen ...

Tips for retrieving the present value of a piped/converted BehaviorSubject

How do I retrieve the current value of the observable generated by readValue() below without subscribing to it? var subject = new BehaviorSubject<Object>({}); observe(): Observable<Object> { return subject.pipe(map(mappingfunction)); } Do ...

Applying the power of Angular function binding within .html() function in d3 visualizations

I am attempting to create a clickable d3 foreignObject span that triggers a function in the component TypeScript file. Below is a snippet of the code I have been working on: .append("foreignObject") .attr("x", x) .attr("y" ...

What is the best way to populate a spinner in an Android app with unique items retrieved from Firebase?

I am currently working on populating a spinner with categories. I have successfully iterated through each category in my database and added them to the spinner. However, I am now looking to fetch only unique values. Take a look at this screenshot; Here&ap ...

Exploring the realm of Typescript custom decorators: The significance behind context

I'm currently working on a custom decorator that will execute decorated functions based on RxJS events. Everything seems to be going well so far, but I'm facing an issue when the function is executed: the context of the this object is lost. I&a ...

Module 'csstype' not found

I am diving into the world of React with TypeScript. After setting up react and react-dom, I also installed @types/react and @types/react-dom which all went smoothly. However, a pesky error message keeps popping up: ERROR in [at-loader] ./node_modules/@t ...

Tips for automatically setting a default radio button selection in Angular 8

I am a beginner in Angular 8 and I am struggling with setting one of the radio buttons to be checked by default. I have attempted adding attributes like [checked]="true", checked but the issue persists. HTML <div class="form-check"> <mat-ra ...

The immutability of the List in JavaScript and its

I am confused about how the size of an Immutable JS List grows. According to the official documentation example at https://facebook.github.io/immutable-js/docs/#/List/push, pushing something into an immutable js List should automatically increase its size ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

Combining Java with Node.js modules

I'm interested in incorporating Angular2 as the client side framework and Java as the server side. However, I am unfamiliar with how to integrate Angular2 into a Java project. Is it advisable to initialize the NPM system within the Java project and in ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Severing Change Detection in Angular 4 Among Child Components

I'm having trouble understanding why the ngDoCheck function continues to be called even when I use ChangeDetectionStrategy.OnPush and changeDetectorRef.detach(). My app has a large number of components, and I want to prevent the change detection in ch ...

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

The Firebase Cloud Function is failing to trigger on the onCreate event within the Firebase Realtime Database

I recently deployed a function to Firebase with the following code: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; console.log('FILE LOADED'); const serviceAccount = require(' ...