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.

Kyle Vassella
  • 2,296
  • 10
  • 32
  • 62
  • 4
    Do you mean [Dynamically access object property using variable](https://stackoverflow.com/q/4244896)? – VLAZ Jan 05 '21 at 09:39
  • 1
    Also, for what it's worth, using OOP and polymorphism here would vastly simplify your code. – VLAZ Jan 05 '21 at 09:45

1 Answers1

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');
SeleM
  • 9,310
  • 5
  • 32
  • 51
  • 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]; }` ? – Kyle Vassella Jan 05 '21 at 10:15
  • 1
    yes you can but be careful: NO '.' (points) between brackets ([a][b] >> is >> a.b) – SeleM Jan 05 '21 at 10:19