2

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
  • 2,678
  • 5
  • 29
  • 65
  • 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

4 Answers4

7

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

Install Lodash

npm install lodash

Import lodash in your file

import _ from 'lodash';

Compare your objects

if(!_.isEqual(obj1, obj2)) {
  //perform your action
}
Evgeny
  • 791
  • 7
  • 15
Jagan
  • 590
  • 1
  • 8
  • 21
3

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,756
  • 7
  • 24
2

If you have use lodash then it's much simplier

_.isEqual(obj1,obj2)

https://lodash.com/

Jay Parmar
  • 368
  • 2
  • 9
0

Try using this function.

const includesObject = (array = [], object = {}) => {
    const filteredArray = array.filter(
      (element) => JSON.stringify(element) === JSON.stringify(object)
    );
    return filteredArray.length > 0 ? true : false;
  };

An example using this function.

import "./styles.css";

export default function App() {
  const array = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
    { id: 4, name: "Four" },
    { id: 5, name: "Five" }
  ];

  const element = { id: 1, name: "One" };

  const includesObject = (array = [], object = {}) => {
    const filteredArray = array.filter(
      (element) => JSON.stringify(element) === JSON.stringify(object)
    );
    return filteredArray.length > 0 ? true : false;
  };

  return (
    <div className="App">
      <h1>{JSON.stringify(element)}</h1>
      {includesObject(array, element) ? (
        <h1>exists</h1>
      ) : (
        <h1>does not exist</h1>
      )}
    </div>
  );
}
Manil Malla
  • 133
  • 8