-1

How to check equality of two objects which is one object type is number other one comes as a string type but a number

var object1 = {  
        x1: "1.000000",
        x2: undefined,
        x3: "1.0",
        x4: "1.0" 
};
var object2 = {  
        x1: 1,
        x2: undefined,
        x2: 1,
        x4: 1 
};

lodash returns false for above scenario. _.isEqual(object1, object2);

Chamie
  • 15
  • 1
  • 5

3 Answers3

1

You can use _.isEqualWith:

var object1 = {  
        x1: "1.000000",
        x2: undefined,
        x3: "1.0",
        x4: "1.0" 
};
var object2 = {  
        x1: 1,
        x2: undefined,
        x3: 1,
        x4: 1 
};

const cmpStr2Num = (val1, val2) => {
  if ((typeof val1 === 'string' && typeof val2 === 'number')
   || (typeof val2 === 'string' && typeof val1 === 'number'))
     return Number(val1) === Number(val2)
}

console.log(_.isEqualWith(object1, object2, cmpStr2Num))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
aleksxor
  • 7,535
  • 1
  • 22
  • 27
0

This works:

var object1 = {
  x1: "1.000000",
  x2: undefined,
  x3: "1.0",
  x4: "1.0"
};
var object2 = {
  x1: 1,
  x2: undefined,
  x2: 1,
  x4: 1
};

const equal = !Object.keys(object1).some(key => object1[key] != object2[key])

console.log(equal)

However, in your example, object2 has a key overwritten (x2 is defined twice), so the objects using the code above are not considered equal

Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100
0

Because string and number are different types.

"1" === 1 // false

Can coerce types of object's values

const coerceObject = object => Object.fromEntries(
    Object.entries(object).map(([key, value]) => {
        return [[key], Number.isNaN(+value) ? value : Number.parseFloat(value)]
    })
)

   _.isEqual(coerceObject(object1), coerceObject(object2));