Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda