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

268
Views
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 answers
Answer question

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 Report

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 Report

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 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!