0

Hi i have array of objects like below,

const arr_obj = [ 
    {
        children: [{}],
        type: "type1",
        updated: "somevalue",
    },
    {
         children: [{}],
         type: "type2",
         updated: "somevalue",
     },
]

now i want to create a new array of object that will have each object as in arr_obj and also add new property "disabled" which is boolean value set to true if type is equal to "type2" if not set to false.

so the expected output is like below

const new_obj = [
    {
        children: [{}],
        type: "type1",
        updated: "somevalue",
        disabled: false,
    },
    {
        children: [{}],
        type: "type2",
        updated: "somevalue",
        disabled: true,
    },
]
    

I have tried like below

const new_obj = React.useMemo(() => {
    arr_obj.map((arr => ({
        ...arr,
        disabled: arr?.type !== "type2" ? false : true,
    }))
}, [arr_obj]
);

but when i log new_obj this is undefined. could someone help me with this. I am new to programming. thanks.

stackuser
  • 374
  • 2
  • 9

1 Answers1

0

You're not returning the result of arr_obj.map so the function returns undefined.

Either

const new_obj = React.useMemo(() => {
  return arr_obj.map((arr) => ({
    ...arr,
    disabled: arr?.type !== "type2" ? false : true,
  }));
}, [arr_obj]);

or drop the braces:

const new_obj = React.useMemo(
  () =>
    arr_obj.map((arr) => ({
      ...arr,
      disabled: arr?.type !== "type2" ? false : true,
    })),
  [arr_obj],
);
AKX
  • 152,115
  • 15
  • 115
  • 172
  • 2
    [There's a well-established dupetarget for this](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value). – T.J. Crowder Jan 21 '22 at 12:33