简体   繁体   中英

I am not able to set the value of property after using filter method even after all the conditions are satisfied

  const eventSeatSelectCallback = (
    
   
    SeatPrice,
    FlightNumber,
    SegmentKey
    
  ) => {
    var postObject = { ...state.post };
      postObject.IsSeatSelected = true;


      postObject.AirPassengerList.filter(
          (x) =>
              x.FlightNumber == FlightNumber.toString() &&
              x.SegmentKey.toString() == SegmentKey.toString() &&
              x.IsSelected == true
      )[0].SeatPrice = SeatPrice;
`
    dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
  };

The line above is giving error in the console as Uncaught TypeError: Cannot set properties of undefined (setting 'SeatPrice') I am trying to set the value of AirPassengerList.SeatPrice to SeatPrice

I want to to set the value of Object AirPassengerList.SeatPrice to the value of paramter SeatPrice

May be you can update the element by index

  const eventSeatSelectCallback = (
    SeatPrice,
    FlightNumber,
    SegmentKey
    
  ) => {

      var postObject = { ...state.post };

      postObject.IsSeatSelected = true;

      const passengerIndex = postObject.AirPassengerList?.findIndex(
          (x) =>
              x.FlightNumber == FlightNumber.toString() &&
              x.SegmentKey.toString() == SegmentKey.toString() &&
              x.IsSelected == true
      );
 
      // update if item is found
      if (passengerIndex !== -1) {
         postObject.AirPassengerList[passengerIndex].SeatPrice = SeatPrice;
         // do you need to updated this only after price update
         // dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
      }   

      dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });  

  };

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM