Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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');

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!