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 badges2 Answers
Reset to default 5Optional 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
评论列表(0条)