Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Compare Equality of Object Key Values with Null

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!