undefined - Safely coalesce on JavaScript sub property - Stack Overflow

I was wondering if there was a cleaner way to do both null coalescing and checking for undefined?For ex

I was wondering if there was a cleaner way to do both null coalescing and checking for undefined?

For example, I have a variable that I want to initialize to a property value of an object that may or may not be defined, in that event null is best because falseyness is a wonderful thing

function DoWork(){
    var foobar = 
      typeof foo !== "undefined" 
        ? typeof foo["bar"] !== "undefined" 
          ? foo["bar"] || null 
          : null 
        : null;

    ...
}

console.log(JSON.stringify(foobar));   //output is either foo["bar"]'s value or null

As you can see this gets messy. I'm curious if there's a better way to handle this kind of thing.

Thanks!

I was wondering if there was a cleaner way to do both null coalescing and checking for undefined?

For example, I have a variable that I want to initialize to a property value of an object that may or may not be defined, in that event null is best because falseyness is a wonderful thing

function DoWork(){
    var foobar = 
      typeof foo !== "undefined" 
        ? typeof foo["bar"] !== "undefined" 
          ? foo["bar"] || null 
          : null 
        : null;

    ...
}

console.log(JSON.stringify(foobar));   //output is either foo["bar"]'s value or null

As you can see this gets messy. I'm curious if there's a better way to handle this kind of thing.

Thanks!

Share Improve this question asked Jan 12, 2017 at 19:14 Matt BourqueMatt Bourque 737 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Optional chaining was introduced in ES2020 and it can be used with the nullish coalescing operator.

const myNestedProp = user?.profile?.name?.last_name ?? null;

// It will print the value of the nested prop `last_name`
// or null if it's undefined
console.log(myNestedProp);

https://github./tc39/proposal-optional-chaining

There is no built-in syntax for this. Libraries like lodash have deep-get methods, that solve this problem:

_.get(x, 'deep.path.property') 

The above will return the value of x.deep.path.property, or undefined if any of the objects along the way, including x, do not exist.

Such a function is not hard to write. You can do so as a thinking exercise, and get the interface you want (with null instead of undefined), or you can look up the lodash.get implementation (you'll need to follow some imports).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744981074a4604445.html

相关推荐

  • undefined - Safely coalesce on JavaScript sub property - Stack Overflow

    I was wondering if there was a cleaner way to do both null coalescing and checking for undefined?For ex

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信