1👍
Optional chaining would be an option but this feature was just released and is not widely available yet.
You should checkout and see supported browsers and environments.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Your code would look something like this
getSomething() {
return this.myInterval?.range?.caption;
}
- [Vuejs]-Moxios not working properly when using window.axios
- [Vuejs]-How to update navbar links after login in vuejs
0👍
If you just want to return either caption
, or null
You can use this simple utility function that receives the path of the nested property you want, and the object you want to get the nested property from, and returns the nested property if the path exists, or null
if it does not.
const getPath = (p, o) => {
if (!p || typeof(p) !== "string" || !o || typeof(o) !== "object") {
return null;
}
return p.reduce((xs, x) =>
(xs && xs[x]) ? xs[x] : null, o)
};
You would then use it in your code like
getSomething() {
return getPath(["myInterval","range","caption"], this);
}
NOTE You can change the default null
value for any fallback value of your need.
Source:stackexchange.com