1

In Angular, I have interfaces which look like this (this is not my code):

export interface Vehicles {
    id: number;
    cars: Car;
    trucks: Truck;
}

Export interface Car {
    make: number;
    model: number;
}

Export interface Truck {
    make: number;
    model: number;
}

My service contains two functions doCarMath() and doTruckMath() that do calculations based on the API's returned values:

vehicleNumbers: Vehicles;

constructor(private http: HttpClient) {
    this.vehicleNumbers = {};
}

callID(id: string): Observable<Vehicles>{
    return this.http.get<Vehicles>(this.myURL+`/${id}`);
}

getMyCarNumbers(id) {
    this.callID(id).subscribe(results =>
    {
        this.vehicleNumbers = results;
    }
}

doCarMath(): number {
    return this.vehicleNumbers.car.make; / this.vehicleNumbers.car.model;
}

doTruckMath(): number {
    return this.vehicleNumbers.truck.make; / this.vehicleNumbers.truck.model;
}

I’d like to combine doCarMath() and doTruckMath() into one doMath() function by passing in an argument to specify either car or truck, like so:

doMath(p_vehicle): number {
    return this.vehicleNumbers.p_vehicle.make/this.vehicleNumbers.p_vehicle.model; // can p_vehicle be used here?
}

How can I use parameter p_vehicle here? The above throws intellisense errors for the p_vehicle parameter, but I don't have the code locally and can't share the error.

2
  • 4
    Do you mean Dynamically access object property using variable? Commented Jan 5, 2021 at 9:39
  • 1
    Also, for what it's worth, using OOP and polymorphism here would vastly simplify your code. Commented Jan 5, 2021 at 9:45

1 Answer 1

2

I think this would do the job:

doMath(p_vehicle): number {
    return this.vehicleNumbers[p_vehicle].make/this.vehicleNumbers[p_vehicle].model; 
}

Then calling the function would be :

doMath('car'); // or this.doMath('car');
doMath('truck'); // or this.doMath('truck');
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Can you stack bracket notation more than once? Originally the properties looked like return this.vehicleNumbers.car.carMake; / this.vehicleNumbers.car.carModel;. Can I also pass in parameters [p_vehicleMake] and [p_vehicleModel] to access carMake and carModel like so: doMath(p_vehicle, p_vehicleMake, p_vehicleModel): number { return this.vehicleNumbers[p_vehicle].[p_vehicleMake]/this.vehicleNumbers[p_vehicle].[p_vehicleModel]; } ?
yes you can but be careful: NO '.' (points) between brackets ([a][b] >> is >> a.b)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.