I'm using the following code to compare two objects and its key value pairs to assure equality. It works great except it doesn't handle null values in fields. I get the following error: TypeError: Cannot convert undefined or null to object.
How could I enhance this to support null values and why does this not work.
Example of expected behavior:
const o1 = {id: 123, name: Brian}
const o2 = {id: 456, name: null}
const objectsEqual = (o1, o2) =>
typeof o1 === 'object' && Object.keys(o1).length > 0
? Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: o1 === o2;
objectsEqual(o1,o2)
//returns false
The problem with your code is "null is an object in javascript"
So when you say typeof o1 === 'object' it evaluates to true, then it tries to evaluate Object.keys(o1).length and throws error here
There can be a simplest solution for this
const objectsEqual = (o1, o2) => JSON.stringify(o1) == JSON.stringify(o2);
If you want to fix your method, then you can change it as below
const objectsEqual = (o1, o2) =>
o1 !== null && o2!== null && typeof o1 === 'object' && Object.keys(o1).length > 0
? Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: o1 === o2;