Destroy an object only if it is right

Suppose I want to destroy a function argument like this

const func = ({field: {subField}}) => subField;

How can I prevent this if you selected an error if the field is undefinedor null?

+4
source share
3 answers

You can use the default value:

const func = ({field: {subField} = {}}) => subField;

It only works with {field: undefined}, but not with, nullas a value. For this, I just used

const func = ({field}) => field == null ? null : field.subField;
// or if you don't care about getting both null or undefined respectively
const func = ({field}) => field && field.subField;

See also javascript test for the existence of a key of nested objects for common solutions.

+3
source

A good way to fix both null and undefined cases is as follows

const func = ({field}) => {
   let subField = null;
   if(field) {
       ({subField} = field);
   }
   return subField
};

If you want to handle the case when the field is undefined, you can simply

const func = ({field: {subField} = {}}) => subField;

, field undefined,

0

You can only destroy and use the subFieldparameter with validation.

var fn = ({ field }, subField = field && field.subField) => subField;

console.log(fn({ field: null }));
Run codeHide result
0
source

All Articles