Home > Enterprise >  ReactJS performing a shallow copy on an object in one step
ReactJS performing a shallow copy on an object in one step

Time:01-08

I am trying to copy the object I have in a component up to a property. I am able to get it to work like this:

 onSubmit: values => {

      data.label = values.label;
      data.userName = values.userName;
      data.recipientUserName = values.recipientUserName
      data.vanityURL = values.vanityURL;
      data.dollarAmount = values.dollarAmount;
      data.textData = values.textData;

I'm new to javascript but this feels very ugly. Is there a way I can do a direct shallow copy without iterating through every field?

The data object is created is passed in at the top as:

export default memo(({ id, data, isConnectable,setElements, removeElements}) => {

  const [show, setShow] = useState(false);
  const handleClose = (e) => {setShow(false)};
  const handleShow = () => setShow(true);

  
  const formik = useFormik({
    initialValues: {
      label: data.label,
      userName: '',
      recipientUserName: '',
      vanityURL: '',
      dollarAmount: '',
      textData: ''
    },
    onSubmit: values => {

      data.label = values.label;
      data.userName = values.userName;
      data.recipientUserName = values.recipientUserName
      data.vanityURL = values.vanityURL;
      data.dollarAmount = values.dollarAmount;
      data.textData = values.textData;
    },
    onReset: (values, { resetForm }) => resetForm(),
  });

return ( ....

The onSubmit is part of a Formik form.

CodePudding user response:

In order to perform shallow copy, you can follow one of these methods.

  1. Use the spread (...) syntax
  2. Use the Object.assign() method
  3. Use the JSON.stringify() and JSON.parse() methods

Example 1

data = {...values}

Example 2

data = Object.assign({}, values)

Example 3

data = JSON.parse(JSON.stringify(values));

CodePudding user response:

You can do

const data = {...value}
  •  Tags:  
  • Related