Reputation: 916
I have an object where one property contains array of objects, I need to destructure it, but when destructuring I don't know how to handle if that property is of empty array
const dataTest1 = {
id: 1,
details: [{f_name_1: "John"}]
}
const {details : [{f_name_1}] = [{}]} = dataTest1 || {}
console.log(f_name_1 ?? 'NA')
const dataTest2 = {
id: 2
}
const {details : [{f_name_2}] = [{}]} = dataTest2 || {}
console.log(f_name_2 ?? 'NA')
const dataTest3 = {
id: 3,
details: []
}
const {details : [{f_name_3}] = [{}]} = dataTest3 || {}
console.log(f_name_3 ?? 'NA')
If you see the first and second case gives me value or fallback value, but when I pass details as an empty array its going error (dataTest3), because I am destructuring first position of array [{}]
, how can I give a default value as empty object
Upvotes: 2
Views: 46
Reputation: 386550
You need an object ad default value for the inner object, because you add only an array if the array is missing, but if exist, you have no object.
const dataTest3 = {
id: 3,
details: []
}
const { details: [{ f_name_3 } = {}] = [] } = dataTest3 || {};
console.log(f_name_3 ?? 'NA');
Upvotes: 2