I have an object array:
cost = [{
id: 'cost01',
client: { id: 'client01', first_name: 'Max', last_name: 'Xam'},
status: 'failed'
}]
I’m trying to create a new array using the object above. When an element is undefined, replace it with the string ‘N/A’
This is the code snippet:
const array = cost.map(
(c: any) => ({
data: [
c.id,
c.client.first_name +
' ' +
c.client.last_name,
c.total_price // <--- this part is missing from cost
? c.total_price
: 'N/A',
c.status
]
})
);
Notice that they array requires c.total_price
, which the initial object cost
does not have. So in this case c.total_price
should be undefined
and returns ‘N/A’
But on the created array, c.total_price
is missing
Returned array:
['cost01', 'Max Xam', 'failed'] -> array length 3
Expected result:
['cost01', 'Max Xam', 'N/A', 'failed'] -> array length 4
How can I modify the code above to reach the expected result? Thanks in advance.
2
Answers
You doesn’t need ternary operator(?).
Just use nullish coalescing(??) or logical OR(||)
Your code is correct. You can use ?? or ||, as Yuvraj mentioned.