Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties:

public id: number;
public modelId: number;
public modelName: string;

Now consider we have an object that looks like this

{id: 1, modelId: 1, modelName: "4"}

What is the best way to assign each property of this object to the respective property of the Vehicle class?

Avoiding manual assignment like below:

this.id = obj.id;
this.modelName = obj.modelName;
this.modelId = obj.modelId;

Answer №1

To assign properties, you can use Object.assign method.

Object.assign(new Vehicle(), {
        id: object.id,
        vehicleName : object.vehicleName,
        vehicleId : object.vehicleId
    })

Answer №2

Check out this code snippet:

class Vehicle {
    public licensePlateNumber?: string;
    public manufacturer?: string;
    public color?: string;

    constructor(details: Vehicle) {
      Object.assign(this, details);
    }
}

You can create a new vehicle like this:

 let car = new Vehicle({licensePlateNumber: "123ABC", manufacturer: "Honda", color: "red"});

See Demo on StackBlitz

Check out the DEMO on Plunker

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

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

Having trouble with executing functions on an express js Route?

I'm currently exploring Node and Express, and I'm encountering an issue when trying to pass a function instead of plain text on my route. It seems that the documentation only mentions using res.send() method with text. Even when attempting to use ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

What are the steps to fix the "Invariant Violation" issue that is linked to the redux store?

During my DOM testing to verify if a dialog box would open upon clicking a button, I encountered an error message: Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , or ...

JSON object name

Here are the specific file locations for loading each of the CSS and JS files. <link href="css/default.css" rel="stylesheet" /> <script src="js/main.js"></script> In XML, the filename is input as shown below ...

Sort through a list of objects using the criteria from a separate array

Looking to apply a filter on an array of objects: const myArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters :["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden&q ...

Switching Story Tense on Facebook Open Graph

After creating a unique story for my facebook app, I discovered that when making a basic story post using the facebook js sdk, the resulting post is in past tense and depicts the object in singular form. For example, instead of saying: John is eating an a ...

Experience feelings of bewilderment when encountering TypeScript and Angular as you navigate through the

Exploring Angular and TypeScript for an Ionic project, I am working on a simple functionality. A button click changes the text displayed, followed by another change after a short delay. I'm facing confusion around why "this.text" does not work as exp ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

Avoiding the storage of POST data in JSON format

Here is some code I am working with: var jsonString = "some string of json"; $.post('proxy.php', { data : jsonString }, function(response) { var print = response; alert(print); }); And this P ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Creating and accessing files within the `dist` folder in Angular 5: A comprehensive guide

After deploying my Angular 5 app to Cloud Foundry, a file named app-number-version is automatically generated in the dist folder with just the version number (e.g., "1.0.0"). My goal is to show this version number in the navigation bar of our app's H ...

What is the best way to automatically post to Slack at regular intervals?

In order to provide users with the option to choose when they receive information from my API, such as daily at 5PM or every Friday at 5PM, I have a configuration page. Once users set their preferred time, I want to send them a Slack message at that specif ...

Sending information from a rails controller to a react component

Wondering how to pass the example @post = Post.all from the controller to React component props while integrating Rails with React via Webpacker. Is it necessary to do this through an API or is there another way? ...

Looking for assistance with converting a basic script into a Joomla 2.5 module and resolving issues with Java integration

I'm having issues with my code in Joomla 2.5. It seems like the Java function is not functioning properly within Joomla. Can someone assist me with troubleshooting this problem? mod_mw_pop_social_traffic.php <?php defined( '_JEXEC' ) or ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

Tips for emptying the search field in primeng multiselect widget

Is it possible to reset the search input field in primeng multiselect? I've been referring to the tutorial on primeng multiselect provided in the following article. https://www.primefaces.org/primeng/showcase/#/multiselect https://i.stack.imgur.com ...

What is the best way to refresh a Component upon sending data to the server?

I'm in the process of developing a cross-platform application. I have a TabView Component that needs to update a tab after sending data to the server. During the initialization (ngOnInit) phase, I dynamically set the content of my tab. However, when I ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...