-1

I've got a form in React, which I need to convert to a different data structure.

The form has the data structure as below -

const [form, useForm] = useState([
    {
      id: 1,
      title: "Section",
      url: "testLink",
      content: [{ id: 3, title: "", url: "" }]
    },
    {
      id: 2,
      title: "Section",
      url: "testLink",
      content: [{ id: 4, title: "", url: "" }]
    }
  ]);

When the user hits submit, I need to delete id property as this is not accepted from the backend.

I'm trying to do this in the following example -

const handleSubmit = (event) => {
    const formData = [...form];
    formData.map((item) => {
      delete item.id;
    });
    console.log(form);
    console.log(formData);
  };

I'm expecting the form and the formData objects to have different properties (formData wouldn't have the id, but form would).

I'm not sure what I'm doing wrong here? Here's a demo from CodeSandbox (I did slightly modify this to get it working asap) - https://codesandbox.io/s/elated-noether-xcr6r?file=/src/App.js

Thanks for taking the time to look into this!

theabrar
  • 360
  • 1
  • 6
  • 15

2 Answers2

0

The spread operator creates a shallow copy of your form object, so when you modify the formData which is referring to the same object form is referring to, it will update the underlying object. Instead, create a deep copy of the form object using lodash's cloneDeep utility.

import cloneDeep from 'lodash/cloneDeep';

const formData = cloneDeep(form);

https://lodash.com/docs/4.17.15#cloneDeep

yondu_udanta
  • 797
  • 1
  • 6
  • 13
0

You will have to clone the object. The easiest way is to parse it to Json and parse it back to object.

See below

  const modifyObject = (event) => {
    const formData = form.map(x=> JSON.parse(JSON.stringify(x)))
    formData.map((item) => {
      delete item.id;
    });
    console.log(form);
    console.log(formData);
  };

There is also other way you could clone the object. read here https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/

Alen.Toma
  • 4,684
  • 2
  • 14
  • 31