¿Cómo puedo obtener las longitudes de los elementos forEach que se verificaron en mi declaración if else?
this.ages = [18, 20, 1]; this.ages.forEach((a) => { //infant if (a >= 0 && a <= 1) { this.id = 1; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: a.length, }); } //adult else if (a >= 12 && a <= 59) { this.id = 3; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: a.length, }); } }); console.log(this.travel);también quiero presionar con el mismo travellerAgeRangeId solo una vez, pero está presionando dos veces.
la salida que obtengo de console.log es:
listOfTravellerCountPerAgeRange: [ {travellerAgeRangeId: 3, travellerCount: undefined}, {travellerAgeRangeId: 3, travellerCount: undefined}, {travellerAgeRangeId: 1, travellerCount: undefined} ]Salida que quiero obtener:
listOfTravellerCountPerAgeRange: [ {travellerAgeRangeId: 3, travellerCount: 2}, {travellerAgeRangeId: 1, travellerCount: 1} ]Actualizado
Aunque su enfoque es inapropiado para hacer esto, de alguna manera resolví su problema; MANIFESTACIÓN
Declara globalmente tu variable
infant = 0; child = 0; adult = 0;Supongamos que tiene una variedad de edades como esta
this.ages = [18, 20, 1, 11, 12, 0.2, 10];Ahora ejecuta un bucle for para contar bebés, niños y adultos.
for (let a = 0; a <= this.ages.length; a++) { if (a >= 0 && a <= 1) { this.infant = this.infant + 1; } else if (a >= 2 && a <= 11) { this.child = this.child + 1; } else if (a >= 12 && a <= 59) { this.adult = this.adult + 1; } }y al ejecutar el ciclo foreach, puede hacer referencia a su variable global de esta manera:
this.ages.forEach((a) => { //infant if (a >= 0 && a <= 1) { this.id = 1; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: this.infant, }); } //child else if (a >= 2 && a <= 11) { this.id = 2; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: this.child, }); } //adult else if (a >= 12 && a <= 59) { this.id = 3; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: this.adult, }); } });Versión antigua
está presionando la longitud del elemento en su propiedad travellerCount que no es una array
Todo lo que necesitas es obtener this.ages longitud.
this.ages = [18, 20, 1]; this.ages.forEach((a) => { //infant if (a >= 0 && a <= 1) { this.id = 1; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: this.ages.length, }); } //adult else if (a >= 12 && a <= 59) { this.id = 3; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: this.ages.length, }); } }); console.log(this.travel);