Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructure object only if it's truthy

Suppose I want to destructure my function argument like this

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

How can I prevent this from throwing an error if field is undefined or null ?

like image 626
Lev Avatar asked Jan 19 '18 10:01

Lev


2 Answers

You might use a default value:

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

It works only with {field: undefined} though, not with null as a value. For that I'd just use

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 existence of nested object key for general solutions.

like image 139
Bergi Avatar answered Sep 27 '22 22:09

Bergi


You could only part destruction and use for subField a parameter with a check.

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

console.log(fn({ field: null }));
like image 29
Nina Scholz Avatar answered Sep 27 '22 21:09

Nina Scholz