Link to home
Start Free TrialLog in
Avatar of Michael Sterling
Michael SterlingFlag for United States of America

asked on

How do I destructure this object to get/set one of the properties?

In react I a have created an object that looks like this:

  const [allValues, setAllValues] = useState({
    username: '',
    email: '',
    passwordOne: '',
    passwordTwo: '',
    error: null,
  });

Open in new window

After doing some processing, at a certain point, I want to set only the value of the error property. How do I do this?
Avatar of ste5an
ste5an
Flag of Germany image

If this is a question about class and objects, then the answer is simply be accessing that property.

If you really want to change the class by removing properties, then it is a simple delete objectVariable.propertyName for each property name to remove.

In a clean OOP approach you would have a second class with an factory method taking your larger source object and returns your new smaller object by internally creating a (deep) copy.
Avatar of Michael Sterling

ASKER

@ste5an: What does accessing that property in code look like? This is my thought:

const {username, email, passwordOne, passwordTwo, error} = [...allValues];
username = "test";

Open in new window

    //How do I now get allValues to be...

    username: '',
    email: '',
    passwordOne: '',
    passwordTwo: '',
    error: 'test'

Open in new window




ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial