I have 2 objects, vehicle1 and vehicle2 objects, for vehicle1 I have a leaflet popup:
`<font size="4"><b>${vehicle1.name}</b></font>
<br>Plates number: ${vehicle1.platesNumber}
<br>Side number: ${vehicle1.sideNumber}
<br>Vehicle color: ${vehicle1.color}
<br>Type of vehicle: ${vehicle1.type}
<br><b>Vehicle range in km: ${vehicle1.rangeKm}</b>
<br><b>Battery level: ${vehicle1.batteryLevelPct}%</b>
<br><b>Reservation ends in: ${vehicle1.reservationEnd}</b>
<br><b>Vehicle is reserved by: ${vehicle1.reservation}</b>
<br><b>Status of car: ${vehicle1.status}</b>
<br><b>Location: ${vehicle1.locationDescription}</b>
<br>Current promotions: ${vehicle1.promotion}
<br>Description of the vehicle: ${vehicle1.description}
<br>Metadata of the vehicle: ${vehicle1.metadata}
<br>ID of the vehicle: ${vehicle1.metadata}`;
I'd like to do the same with vehicle2, just to swap between objects, so I want something like that:
`<font size="4"><b>${vehicle2.name}</b></font>
<br>Plates number: ${vehicle2.platesNumber}
<br>Side number: ${vehicle2.sideNumber}
<br>Vehicle color: ${vehicle2.color}
<br>Type of vehicle: ${vehicle2.type}
<br><b>Vehicle range in km: ${vehicle2.rangeKm}</b>
<br><b>Battery level: ${vehicle2.batteryLevelPct}%</b>
<br><b>Reservation ends in: ${vehicle2.reservationEnd}</b>
<br><b>Vehicle is reserved by: ${vehicle2.reservation}</b>
<br><b>Status of car: ${vehicle2.status}</b>
<br><b>Location: ${vehicle2.locationDescription}</b>
<br>Current promotions: ${vehicle2.promotion}
<br>Description of the vehicle: ${vehicle2.description}
<br>Metadata of the vehicle: ${vehicle2.metadata}
<br>ID of the vehicle: ${vehicle2.metadata}`;
But I don't want to repeat code like this. I tried putting it into the object with 'this' keyword, but it didn't work. Thanks for help!
CodePudding user response:
const vehicleArray = [vehicle1,vehicle2]; //have your vehicle objects inside an array
// call Array map function for the vehicleArray
const transformedVehicleArray = vehicleArray.map((vehicle) =>
`<font size="4"><b>${vehicle.name}</b></font>
<br>Plates number: ${vehicle.platesNumber}
<br>Side number: ${vehicle.sideNumber}
<br>Vehicle color: ${vehicle.color}
<br>Type of vehicle: ${vehicle.type}
<br><b>Vehicle range in km: ${vehicle.rangeKm}</b>
<br><b>Battery level: ${vehicle.batteryLevelPct}%</b>
<br><b>Reservation ends in: ${vehicle.reservationEnd}</b>
<br><b>Vehicle is reserved by: ${vehicle.reservation}</b>
<br><b>Status of car: ${vehicle.status}</b>
<br><b>Location: ${vehicle.locationDescription}</b>
<br>Current promotions: ${vehicle.promotion}
<br>Description of the vehicle: ${vehicle.description}
<br>Metadata of the vehicle: ${vehicle.metadata}
<br>ID of the vehicle: ${vehicle.metadata}`
);
//now you can access transformedVehicleArray[0] and transformedVehicleArray[1] to get the html block for vehicle1 and vehicle2 respectively