2

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

2
  • 1
    I'll be honest: this looks near-impossible to understand for a code reviewer, what are you actually trying to achieve (i.e. what does your data represent, and what are you turning it into, for what reason) that makes you want to use this approach? Commented Dec 22, 2021 at 17:25
  • Thanks for pointing, Since i have not f_name_3, around 7 to 8 properties are there so instead of writing every place dataTest3?.details[0]?.f_name_3 like this for all 8 properties and using it multiple places thought of writing in this way. let me know if this is not the right way to add the code like this Commented Dec 22, 2021 at 17:59

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.