简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM