3

I need to destructure a nested object. what is the best way to avoid exceptions when some of the nested properties are missing, while assigning those who do exist?

const data = {
  title: 'hello',
  // nest: {
  //   road: 5
  // }
};

const { title, nest: { road = '' } } = data;

console.log(road);
/** i want it to return '' or undefined. 
 *  actually it returns: Cannot match against 'undefined' or 'null'
 * 
*/
console.log(title)
/** i want it to return 'hello'
 * actually: never got there as there was an exception.
 */
LiranC
  • 2,400
  • 1
  • 27
  • 55
  • Know your `Object` types that you want to deconstruct. That is what Javascript's type system is telling you. Anyway, if there is no `road` property, just provide an empty parent object `nest: {}`. –  Aug 30 '17 at 13:55

1 Answers1

5

You can assign in a parent object level to empty object (or with value) even if it has further nested object destruction:

const { title, nest: { road = '<default road>' } = {} } = data;

const data = {
  title: 'hello',
   //nest: {
   //  road: 5
   //}
};

const { title, nest: { road = '<default road>' } = {} } = data;

console.log(title);
console.log(road);

And also, you are doing it wrong, if you are destructing using

{title: englishTitle} = {title: 1234}

then, you should use englishTitle to get the value 1234, and not title, or use

{title} = {title: 1234}

and use title to get 1234

FZs
  • 16,581
  • 13
  • 41
  • 50
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32