为几个对象制作灵活的文本

Making flexible piece of text for a couple of objects

我有 2 个对象,vehicle1 和 vehicle2 对象,对于 vehicle1,我有一个传单弹出窗口:

`<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}`;

我想对 vehicle2 做同样的事情,只是为了在对象之间交换,所以我想要这样的东西:

`<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}`;

但我不想重复这样的代码。我尝试用 'this' 关键字将它放入对象中,但它没有用。感谢您的帮助!

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