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

undefined - Safely coalesce on JavaScript sub property - Stack Overflow

programmeradmin3浏览0评论

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).

发布评论

评论列表(0)

  1. 暂无评论