Home > Mobile >  Javascript - comparing if 2 objects are the same
Javascript - comparing if 2 objects are the same

Time:08-18

I have 2 objects that will always have the same amount of properties just in occasion the values may be different.

I am attempting to do a check against the 2 objects to see if they are the same value

I decided to try and handle this using the .every method but all results are returning false even when I am expecting it to be true.

How can I compare 2 objects to see they are equal?

Here is a code snippet

const priceOne = {
"price": 14.31,
"taxes": 2.00,
"total": 16.31
}

const priceTwo = {
"price": 14.31,
"taxes": 2.00,
"total": 16.31
}

const comparePrice = Object.keys(priceOne).every((item, index) => {
      item === Object.keys(priceTwo)[index] ?  true :  false
    })
    
console.log(comparePrice)

CodePudding user response:

I would JSON.stringify() and compare that way .. IE:

if ( JSON.stringify(priceOne) === JSON.stringify(priceTwo) ){ 

CodePudding user response:

When objects are different:

     const priceOne = {
            "price": 14.31,
            "taxes": 2.00,
            "total": 16.31
      }

      const priceTwo = {
            "price": 12.31,
            "taxes": 2.00,
            "total": 16.31
        }

let comparePrice = true

 for (let key in priceOne){
    if(priceOne[key] != priceTwo[key]){
       comparePrice = false
     }`
  }`

the variable will be false when objects are the same :

const priceOne = {
       "price": 14.31,
       "taxes": 2.00,
       "total": 16.31
 }

const priceTwo = {
      "price": 14.31,
      "taxes": 2.00,
      "total": 16.31
}

the result will be true.

I hope I helped

  • Related