Skip to content
Advertisement

React | JavaScript : Need to compare two objects

Objective:

I need to check if the form has been edited by the user or not. If yes, then I will call the axios.put() function.

Issue:

Since in JS, obj1 = { name: “John “} !== obj2 = { name: “John” } I am looking for a better way to compare two objects.

My way(seems inefficient) :

const intialAddress= {
   city: "CA"
   line1: "testline1"
   line2: "testline2"
   phone: "7772815615"
   pin: "1234"
   state: "CA"
}

const [address, setAddress] = useState(initialAddress);
let addressFinalValue = {};
const addressValue = (e) => {
        addressFinalValue[e.target.name] = e.target.value;
    };

/***************************
 * The way I am doing it 
 **************************/

const submitHandler = (e) => {
  e.preventDefault();
  setAddress(addressFinalValue);
  if ( address.line1 !== initialAddress.line1 || address.line2 !== initialAddress.line2 || etc ... ) {
     // axios.put()
  } 
};

return (
    <form onSubmit={submitHandler}>
            <div className="form-group">
                <input id="address-line-1" className="form-control" value={address.line1}
                    onChange={addressValue} name="line1" type="text" placeholder="Line 1" />
            </div>

                   //  multiple input fields here   //

        <button className="btn btn-success">Save Address & Continue</button>
    </form>
)

I would really appreciate the help. Thanks in advance.

Advertisement

Answer

If you have use lodash then it’s much simplier

_.isEqual(obj1,obj2)

https://lodash.com/

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement