0

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.

Karan Kumar
  • 1,726
  • 2
  • 12
  • 39
  • 1
    Does this answer your question? [How to compare two objects and get key-value pairs of their differences?](https://stackoverflow.com/questions/33232823/how-to-compare-two-objects-and-get-key-value-pairs-of-their-differences) – Józef Podlecki Jun 25 '20 at 19:15
  • Thanks. But this doesn't work. "diff" is showing error. since it isnt an inbuilt function. – Karan Kumar Jun 25 '20 at 19:21
  • Have you read the whole answer in that question? This is not builtin function. You have to declare `diff` somewhere – Józef Podlecki Jun 25 '20 at 19:22
  • @KaranKumar you don't need to update the question when it is solved, when you mark an answer as accepted it will be marked as "solved" automatically. – Brian Thompson Jun 25 '20 at 19:33

3 Answers3

1

If you have use lodash then it's much simplier

_.isEqual(obj1,obj2)

https://lodash.com/

Jay Parmar
  • 338
  • 2
  • 8
1

I'd suggest to use Lodash. check this https://lodash.com/docs/3.10.1#isEqual

Install Lodash

npn install lodash --save

Import lodash in your file

import _ from 'lodash';

Compare your objects

if(!_.isEqual(obj1, obj2) {
  //perform your action
}
Jagan
  • 461
  • 1
  • 7
  • 19
0

Comparing two objects without using lodash:

function compareObjs(obj1,obj2){
   return JSON.stringify(obj1)===JSON.stringify(obj2);
}
console.log(compareObjs({name:"stack"},{name:"overflow"}));
Hritik Sharma
  • 1,016
  • 3
  • 11