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?
var dayMargin = items.hasOwnProperty('dayMargin') ? items.dayMargin.formattedValue : "--";
You could also use conditional chaining and the null coalescing operator:
var dayMargin = items?.dayMargin.formattedValue ?? "--";
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 : '--'
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)