I’m receiving the data where a lot of fields are null, and I have to populate something if the field is null.
like in the below data
{ //... IGM_ETD: '2021-11-27T23:59:00+05:00', milestatus: null, transit_depart: null, etd_atd: null, // around 200+ fields }
As here, the transit_depart is null, I’m using the ternary operator to put something in return if the data is null like this ;
// this is a reproducible example. // there are some other styles and comp to display if/else part {transit_depart ? <>{transit_depart}</> : <>Not Available<>}
This is working as expected but the problem is I have around 200+ fields like this and if I follow this then in the future if we have to make any UI change then we will be changing all the relevant code here. So how to avoid it or how can we can manage this.
Advertisement
Answer
Replacing unavailable data with a default value requires a previous analysis. Most probably many fields may have different default values.
For example, 0
for certain amounts; now
for some dates, but first day of the year
for others; " "
, "TBD"
or "N/A"
for some strings…
You need a method to map some fields to specific default values for those fields, and a final failover default for the rest of the fields.
For the sample data provided
let data = { IGM_ETD: '2021-11-27T23:59:00+05:00', milestatus: null, transit_depart: null, etd_atd: null }
we might want that milestatus
default be 0, the transit_depart
default be the Jan 1st 2021, and all the other fields default to "N/A"
; we could define a defaults object
{ milestatus: 0, transit_depart: new Date('2021-01-01') }
and a setDefaults
function to map the data fields to the defaults
function setDefaults(data) { const someDefaults = { milestatus: 0, transit_depart: new Date('2021-01-01') } const theDefault = "N/A"; for (const [key, value] of Object.entries(data)) { if (value==null) { if (someDefaults[key]!=null) { data[key] = someDefaults[key] } else { data[key] = theDefault; } } } return data; }
running the function against the sample data
setDefaults(data)
would transform data
to contain
{ IGM_ETD:"2021-11-27T23:59:00+05:00", milestatus:0, transit_depart:"2021-01-01T00:00:00.000Z", etd_atd:"N/A" }