Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

destructuring nested level of array of object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading