Home  >  Article  >  Web Front-end  >  How to compare two objects for equality in JavaScript

How to compare two objects for equality in JavaScript

不言
不言forward
2019-02-25 10:29:532912browse

The content of this article is about the method of comparing two objects for equality in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This is a question I was asked by the interviewer during an interview

In this interview question

Equal: refers to the number of attributes of the object Equal

There are two obj

let obj1 = {
    name:'李德华',
    age:18,
    price:NaN
}

let obj2 = {
    name:'张德华',
    age:18,
    price:NaN
}

I can think of a solution

function compare(obj1,obj2){
    if(Object.keys(obj1).length != Object.keys(obj2).length){
      return false
    }else{
      for(key in obj1){
        if(obj2.hasOwnProperty(key)){
            if( !Object.is(obj1[key],obj2[key])){
                return false;
            }
        }else{
          return false
        }
      }
      return true
    }
}

Thinking about the solution process

  • Because obj has no length, I can only convert it into an array through Object.keys()

  • to enter the second step, whether the properties in the object exist in another obj. Object.hasOwnProperty() is used here to only compare the properties in the object (to avoid obj inheriting the properties of the parent)

  • carries the basis of the second step to compare the property values. Comparison. Object.is() in ES6 to avoid the problem that NaN is not equal to itself

or use _.isEqual

in Underscore.js

The above is the detailed content of How to compare two objects for equality in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete