Search code examples
javascriptconditional-operator

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?


Solution

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

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

    var dayMargin = items?.dayMargin.formattedValue ?? "--";