Strategies for Safely Assigning Firestore Data to an Object Without Losing Null Values

I am dealing with a class setup as follows:

export class Car{
    color='';
    topSpeed=0;
    wheels = 4;
}

Within my Firestore database, there exists a document titled "car" with values:

color:red
topSpeed:230

(note that the 'wheels' key is missing)

Upon retrieving and assigning data, the process resembles something like this:

firebaseController.getCar().subscribe(car=>{
   this.car = car
}

While everything seems to be functioning properly, the issue arises when the 'wheels' property gets overwritten with "undefined". Is there a way to prevent variables from being overwritten if a key does not exist or if the value for that key is null?

Answer №1

To implement merging properties, you can utilize the spread operator:

this.vehicle = { ...(new Vehicle()), ...vehicle };

By doing this, the variable this.vehicle will inherit the default attributes from new Vehicle() and then incorporate its unique properties from ...vehicle only if they are different from undefined.

Nonetheless, it is advisable to avoid using a class in this context because this.vehicle would not truly be an instance of Vehicle. If Vehicle includes a method like honk(), you will not be able to execute this.vehicle.honk(). Perhaps, it might be more suitable to employ a constructor for Vehicle in such a scenario. Alternatively, if the object does not contain any methods, utilizing interfaces could be a better option:

interface Vehicle {
    color?: string;
    topSpeed?: number;
    wheels?: number
}

const defaultVehicle: Vehicle = {
    color: '',
    topSpeed: 10,
    wheels: 4
};

// ....

this.vehicle = {...defaultVehicle, ...vehicle }

Where vehicle is the object retrieved from Firebase.

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

Expanding a TypeScript interface across different modules

For my project, I am working with Highcharts typings and encountered a need to extend certain object/interfaces it defines by adding some custom properties. Here is an example: declare namespace Chart { interface ChartOptions extends Highcharts.ChartOpt ...

Change the background color of a span element dynamically

I am currently working on implementing dynamic background coloring for a span tag in my Angular view that displays document types. The code snippet provided is as follows: <mat-card *ngFor="let record of records"> <span class="doc ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

Looking for assistance in setting up a straightforward TypeScript Preact application

I recently started exploring preact and I'm attempting to create a basic app using typescript in preact. I've noticed that their default and typescript templates include extras like jest and testing, which I don't necessarily require. Althou ...

I am encountering a problem with my component as the Angular Directive is missing

Recently, I incorporated a customized directive into my Angular app to allow file uploads via drag and drop. However, I encountered an issue where the command line kept throwing an error stating that my function does not exist within my component. Propert ...

Receiving user input in Angular 6 for a function

Need help getting input from a text box and passing it to a function. Encountering the error message "_co.randomCode is not a function." New to Angular and have tried various approaches but can't seem to solve this issue. app.component.html <div ...

What is the best way to incorporate a background image using ngStyle?

I need help populating multiple cards in the following way: <mdl-card *ngFor="let product of templates" class="demo-card-event" mdl-shadow="2" [ngStyle]="{ 'background-color': 'lightgray' }"> <mdl-card-title mdl-card-expan ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

Do not include the node_modules directory in the TypeScript compilation process, except for a specific subdirectory that is

To exclude the entire node_modules directory from TypeScript compilation, you can modify the tsconfig.json file like so: { "compilerOptions": { "module": "commonjs", "sourceMap": true, "target": "es6" }, "exclude": [ ...

Utilize static information within an Angular component

I'm working on an Angular project in my localhost and I want to have two routed components that share the same data. One component will display the data, while the other will handle the data. In simpler terms, I need two webpages: one with an input f ...

Guide on setting up component from service to display toast notifications

I am looking to implement a global toast service in my application with custom styles and HTML for the toasts. Currently, I am using ng2-toastr. For example, let's say I have a component A which contains a button in its view: <button (click)="show ...

Angular | Switching ngTemplateOutlet dynamically based on screen size for improved responsiveness

Currently, I am developing a web application using Angular in combination with Angular Flexbox. Throughout my project, I make use of numerous ng-templates to ensure that the HTML code blocks are not repeated, following the DRY (Don't Repeat Yourself) ...

Angular: Simplifying complex JSON structures

Is there a built-in feature in Angular for flattening JSON data and then restructuring it back? I came across some code below, but I'm wondering if Angular offers any native library functions for this task. If not, I may consider incorporating this fu ...

Dismiss the necessity of imports in Angular

I am facing an issue with using a library in Angular, specifically the cubing npm package. This library is designed to run in both the browser and node environments, with specific code for each. I want it to run in the browser, but when compiling with Angu ...

The navigation bar text overflows when the sidebar is collapsed into icons

My sidebar contains icons and a menu name. When the screen size is smaller than a certain amount, the sidebar collapses to show only the icon and hides the menu name. Here is the structure of the navbar: <nav id="sidebar" [ngClass]="{active: barActive} ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png <ng-container matColumnDef="scheduled"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th> <td mat-cell *matCellDef="let station"> ...

Personalized Functions Using Material Design Expansion Panel Header Icon

Here's a unique material design accordion with an icon added to the panel header. I want to invoke my function 'myFun()' on click event, but currently, the expansion panel is toggling each time it's clicked (which is not the desired beh ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

Navigating with Angular 2: Redirecting Azure AD login URI

I am currently exploring Azure AD integration for logging into an Angular 2 application. The Github link provided below demonstrates a simple method to log in without the use of any authentication libraries. Sign in via Microsoft Graph using Typescript an ...