skip to Main Content

i want to return a object to my array but it return number values in arry

const mappingFunction = (values: any) => {
    values.forEach((reason: any) => {
      const selectedReasons: any = [];
      if (reason?.isChecked === "false") {
        selectedReasons?.push(reason);
      }
    });
    setSelectedReasons(values);
  };

2

Answers


  1. Declare the variable before the loop, not for every item:

    const mappingFunction = (values: any) => {
      const selectedReasons: any = [];
      values.forEach((reason: any) => {
        if (reason?.isChecked === "false") {
          selectedReasons?.push(reason);
        }
      });
      setSelectedReasons(values);
    };
    
    Login or Signup to reply.
  2. You define selectedReasons inside your loop which will create a new instance on every iteration. You also pass setSelectedReasons to the values that the function takes in.

    You could use the filter method to get only the values where the reason is false.

    const mappingFunction = (values: any) => {
      const filteredValues = values.filter(
        (reason: any) => reason?.isChecked === "false"
      );
      setSelectedReasons(filteredValues);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search