最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - destructure object only if it's truthy - Stack Overflow

programmeradmin4浏览0评论

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 ?

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 ?

Share Improve this question edited Jan 19, 2018 at 10:07 Lev asked Jan 19, 2018 at 10:02 LevLev 15.7k16 gold badges63 silver badges91 bronze badges 1
  • const func = ({field: subField}) => subField; – nichtgian Commented Jan 19, 2018 at 10:05
Add a ment  | 

3 Answers 3

Reset to default 11

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.

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

A good way to fix both the cases of null and undefined is the following

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

If you only want to handle the case when field is undefined, you could just to

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

whereby if field is undefined the default empty object is used as its value

发布评论

评论列表(0)

  1. 暂无评论