I am trying to loop through the components array and join all the tire component descriptions with a comma (, ) if there are multiple.
let dataForTemplate = {};
incident = {
complaint_id: 55556473,
components: [{
component_id: 263,
name: 'SEAT BELTS',
description: '150000 SEAT BELTS',
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: false,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 1
},
{
component_id: 300,
name: 'TIRES',
description: '190000 TIRES',
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: true,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 17
},
{
component_id: 1025,
name: 'CHILD SEAT:VEHICLE TETHER ANCHOR',
description: '532000 CHILD SEAT:VEHICLE TETHER ANCHOR',
is_public: true,
is_vehicle: false,
is_equipment: false,
is_tire: false,
is_child_seat: true,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 4
}
]
};
Here is what I am trying:
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components.map((e) => {
console.log(e);
if (e.is_tire) {
return ${e.description};
}
}).join(' ,');
}
console.log(dataForTemplate);
Current output: {tire_components: " ,190000 TIRES ,"}
Expected output: {tire_components: "190000 TIRES"}
It should only join string with comma if there are multiple descriptions satisfying the condition.
:with,? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…mapcall, you have an array of results,["", "190000 TIRES", ""]. You want tofilterfirst to include only the relevant ones.