Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda