最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - React | JavaScript : Need to compare two objects - Stack Overflow

programmeradmin1浏览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.

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.

Share Improve this question edited Jun 25, 2020 at 19:34 Karan Kumar asked Jun 25, 2020 at 19:12 Karan KumarKaran Kumar 3,1768 gold badges37 silver badges77 bronze badges 4
  • 1 Does this answer your question? How to compare two objects and get key-value pairs of their differences? – Józef Podlecki Commented Jun 25, 2020 at 19:15
  • Thanks. But this doesn't work. "diff" is showing error. since it isnt an inbuilt function. – Karan Kumar Commented Jun 25, 2020 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 Commented Jun 25, 2020 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 Commented Jun 25, 2020 at 19:33
Add a comment  | 

5 Answers 5

Reset to default 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
}

Comparing two objects without using lodash:

function compareObjs(obj1,obj2){
   return JSON.stringify(obj1)===JSON.stringify(obj2);
}
console.log(compareObjs({name:"stack"},{name:"overflow"}));

If you have use lodash then it's much simplier

_.isEqual(obj1,obj2)

https://lodash.com/

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>
  );
}

My personal preference is not to install packages for simple things.

Since I don't see it mentioned here, the choice I went for in similar situation is shallowEqual (or deepEqual if you need it). Examples here:

https://dmitripavlutin.com/how-to-compare-objects-in-javascript/

发布评论

评论列表(0)

  1. 暂无评论