Allusion to a intricate data component

In my code, I have a model that is being represented by a class.

For example, let's consider the model of a car:

export class Car
{
    public name : string;
    public color: string;
    public power : number;
    public service : boolean;
}

All cars are stored in a list.

cars : Array <Car>;

Now, I am looking to create a function that can modify one attribute of a car dynamically.

For instance, changing the color of the first car or the name of the second car.

What would be the most efficient way to pass a reference to a specific car and its attribute as parameters for this function?

From what I understand, using something like

 cars[0].name 

would only pass the value, not a reference within the function.

I can target a car through the index of the array, but for the attribute, using a string for interpretation doesn't seem very optimal. Do you have any better suggestions for how to approach this problem?

Answer №1

Discover the Power of Advanced Types with indexed types! Revolutionize the way you handle dynamic type properties in a safe and efficient manner:

interface Car {
    name: string;
    color: string;
    power: number;
    service: boolean;
}

class CarContainer {
    public cars: Car[] = [];

    updateCar<K extends keyof Car, V extends Car[K]>(index: number, key: K, value: V) {
        let selectedCar = this.cars[index];
        if (selectedCar) {
            selectedCar[key] = value;
        } 
    }
}


let c = new CarContainer();
c.cars.push({
    name: "Old Jalopy",
    color: "black",
    power: 0,
    service: false,
});

// Time for a power upgrade!
c.updateCar(0, "name", "Tesla Roadster");
c.updateCar(0, "power", 100000000);

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

How can I retrieve the row index in an Angular Mat-Table that has expandable content?

Having a mat-table with expandable content on a page, I am seeking a solution to record the row number of the table when clicked. While I successfully achieved this with a regular table in the HTML file using: <tr mat-row *matRowDef="let row; columns: ...

Executing a series of promises sequentially and pausing to finish execution

I have been attempting to run a loop where a promise and its respective then method are created for each iteration. My goal is to only print 'Done' once all promises have been executed in order. However, no matter what I try, 'done' alw ...

What is the importance of fulfilling a promise in resolving a response?

I have a promise structured as follows: let promise = new Promise((resolve, reject) => { axios.post("https://httpbin.org/post", params, header) .then(response => { resolve(Object.assign({}, response.data)); // resolve("aaaa"); ...

Attempting to retrieve JSON data and present it in a grid layout

I have a JSON file with the following data: { "rooms":[ { "id": "1", "name": "living", "Description": "The living room", "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz7 ...

Checking to see if an object is null using Javascript/AngularJS

Below is the code snippet: function getBestBlock(size){ var bestBlock = {}; var blockEnteredTest = true; for(var i = 0; i < $scope.blocks.length; i++) { if($scope.blocks[i].state == "Free") { i ...

Ways to transfer selected options from a dropdown menu to a higher-level component

I am currently in the process of configuring a modal component that showcases various data from a specific record to the user. The user is provided with a Bulma dropdown component for each field, enabling them to make changes as needed. To streamline the c ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...

The Kendo UI Grid's cancel function fails to revert back to the original data

I am facing an issue with a kendo grid that is embedded inside a kendo window template. This grid gets its data from another grid on the main UI, following a model hierarchy of Fund -> Currency -> Allocations. The main UI grid displays the entire dat ...

Issues with the drop-down menu in the <s:select> element arise when attempting to set the

While utilizing a Map to populate the Struts2 tag <s:select >, I have noticed that when the form is submitted multiple times, a blank line is added at the end of the list. For example, if the Map contains 2 key-value pairs, it displays 3 records and ...

What steps can be taken to resolve a Mediasoup installation error in a Node.js environment?

While attempting to install the mediasoup library, I ran into an error that has me stumped. If anyone has encountered this issue before or knows how to solve it, any assistance would be greatly appreciated. > <a href="/cdn-cgi/l/email-protection" c ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

The angular-oauth2-oidc library is having issues loading the jsrsasign module

I'm currently working on upgrading a dependency in Angular for a project that was forked from: https://github.com/mgechev/angular-seed The dependency in question is located at: https://github.com/manfredsteyer/angular-oauth2-oidc. However, I'm f ...

I am interested in retrieving a variable from a function

this is some unique HTML code <form id="upload"> <label for="file">Choose a File to Upload</label> <input type="file" id="file" accept=".json"> <butto ...

Issue with React component timer becoming unsynchronized with numeric input field

My number field and countdown timer are not staying synchronized. Even though I can start and pause the countdown, whenever I try to change the number value after pausing, the numbers get out of sync. The gap between the two values keeps growing as time p ...

Encountered an issue with Webpack 5 - A ReferenceError was thrown: require is not recognized

I encountered an error while attempting to access the main page of my app in the browser: Uncaught ReferenceError: require is not defined at Object.events (main.bundle.js:90508:1) at __webpack_require__ (main.bundle.js:91217:33) at fn (main.bundle.js:91451 ...

Use the Nodejs HTTP.get() function to include a custom user agent

I am currently developing an API that involves making GET requests to the musicBrainz API using node.js and express. Unfortunately, my requests are being denied due to the absence of a User-Agent header, as stated in their guidelines: This is the code sn ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

"Using regular expressions in a MongoDB find() query does not provide the desired

app.get("/expenses/:month", async (req, res) => { const { month } = req.params; const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d"); console.log(regexp); const allExpenses ...

Implicated Generic in TypeScript

Is there a way to simplify my class A implementation? export class A<TB extends B<TC>, TC> implements TD<TB, TC> { make(): TC {} } Currently, I have to specify the TC type every time I create an instance of A: class CTest {} class BTes ...