I am looking for a way to default a javascript value if something in an object with 3+ depth is undefined. For instance, something like this:
var finalData = {};
const data = {};
finalData.transactions = data.b.transactions || [];
instead of:
var finalData = {};
const data = {};
if (data.b)
finalData.transactions = data.b.transactions || [];
else
finalData.transactions = [];
The problem with the first line is it will fail with an undefined access issue if data does not have a child named b.
You can achieve this by combining && and ||:
finalData.transactions = (data && data.b && data.b.transactions) || [];
You can do it like below:
var finalData = {};
const data = {};
finalData.transactions = data.b && data.b.transactions || [];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With