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

176
Vistas
How to handle JavaScript objects (parsed JSON) that contain null?

I'm using JavaScript/jQuery to fetch data as json via an ajax call. The json is then parsed to a JavaScript object. Let's call the object var.

Now I want to assign a value from the object to a variable:

let publicationDay = val["work-summary"][0]["publication-date"]["day"]["value"]

This works, as long this value exists. However, for some results, the object contains null not for ["value"] but for ["day"] (as shown below)

val["work-summary"][0]["publication-date"]["day"] // is null

In this case, let publicationDay = val["work-summary"][0]["publication-date"]["day"]["value"] will throw the following error:

Uncaught TypeError: val['work-summary'][0]['publication-date'].day is null

and the code execution is stopped. Sure, I can check whether val["work-summary"][0]["publication-date"]["day"] === null, but what would be the most elegant way to handle this case? Maybe, in the future even

val['work-summary'][0]['publication-date'] // is null

may occur and my check for null does not work.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Depends heavily on your context but here’s some examples.

const publicationDate = val['work-summary'][0]['publication-date'];

// usage
console.log(publicationDate && publicationDate.day && publicationDate.day.value); // very basic
console.log(publicationDate?.day?.value); // optional chaining, better if supported by your environment (should be)
console.log(get(publicationDate, “day.value”)); // lodash get()

about 4 years ago · Juan Pablo Isaza Denunciar

0

I would recommend trying optional chaining. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Assuming that any of those values could be null:

let publicationDay = val?.["work-summary"]?.[0]?.["publication-date"]?.["day"]?.["value"]

It will set the variable to either day.value or undefined

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