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

275
Vistas
Can check for JS object value be replaced with a ternary?

I have an API that returns objects in JSON. Not all of them have the same fields, some have a few more. I am populating a table, and want a cleaner way to do the following:

if (items.hasOwnProperty('dayMargin')) {
    var dayMargin = items.dayMargin.formattedValue;
} else {
    var dayMargin = "--"
}

So if that object has 'dayMargin' it will either output the value, or "--" if that key / value doesn't exist. I want to clean this up, as there are 10+ similar scenarios. Is it possible to use a ternary operator here? If so, how?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

var dayMargin = items.hasOwnProperty('dayMargin') ? items.dayMargin.formattedValue : "--";

You could also use conditional chaining and the null coalescing operator:

var dayMargin = items?.dayMargin.formattedValue ?? "--";
about 4 years ago · Santiago Trujillo Denunciar

0

Im not sure If i understand your problem, however you can create a ternary oparator like this:

const dayMargin = items.hasOwnProperty('dayMargin') ? items.dayMargin.formattedValue : '--'
about 4 years ago · Santiago Trujillo Denunciar

0

The null coalescing operator is used to do exactly what you want.

//Object formating example
let items = {
  dayMargin: 'im here',
}
items.dayMargin = items.dayMargin ?? '--'
items.nightMargin = items.nightMargin ?? '--'
console.log(items)

//Property extracting example
let items2 = {
  dayMargin: {formatedValue:'im here'},
}
const dayMargin = items2.dayMargin?.formatedValue ?? '--'
const nightMargin = items2.nightMargin?.formatedValue ?? '--'
console.log(dayMargin, nightMargin)

about 4 years ago · Santiago Trujillo 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