0

I have this object as a state in reactjs. I want to add another object inside the "childoptions: []" array which is nested inside the options array on button click.

How can I achieve this, pls help...

  const [select1, setSelect1] = useState({
    id: uuid(),
    type: 'select',
    properties: {
      label: 'Select1',
      options: [
        // {
        //   id: uuid(),
        //   optionName: 'red ',
        //   value: '',
        //   childOptions: [],
        // },
        // {
        //   id: uuid(),
        //   optionName: 'green ',
        //   value: '',
        //   childOptions: [],
        // },
        // {
        //   id: uuid(),
        //   optionName: 'blue ',
        //   value: '',
        //   childOptions: [],
        // },
      ],
    },
    parentId: null,
  });

1 Answers1

0

This is achievable by copy the prevState in the new state with the new object inserted inside the options array.

A more detailed explanation could be found at https://stackoverflow.com/a/26254086/9095807

setSelect1((prevState) => {
  return {
    ...prevState,
    properties: {
      label: 'Select1',
      options: prevState.properties.options.map(obj => obj.id === id ? { ...obj, childOptions: [...obj.childOptions, newChildOptions] } : obj),
    }
  }
})
Girgetto
  • 1,010
  • 9
  • 19
  • Hello @Girgetto, thanks for your answer. I want here to insert an object inside the "childoptions" property of "options" array. this is a more nested object. – Amritpal Singh Jul 07 '22 at 10:09
  • Got it, I've changed the code, to be able to perform it you'll need to know the `id` of the object where you would like to add the `childOptions` array and the `newChildOptions` – Girgetto Jul 07 '22 at 10:49