Let's say I have a JavaScript object like:
var obj = {};
obj.computers = {};
obj.computers.favorite = "Commodore 64";
obj.computers.popular = "Apple";
Now, I can easily check for null like:
if(obj != 'undefined' && obj != null) {
if(obj.computers != 'undefined' && obj.computers != null)) {
.....
As you can see, if I need to see if obj.computers.favorite
has been set, I have to really nest some conditional logic there. Some of our objects go 3, 4, 5 levels deep.
This is what I would like to be able to do:
var fav = obj.computers.favorite || 'Unknown';
But I realize I would need to wrap that in some method. Something like:
var fav = getValueOrDefault(obj.computers.favorite, 'Unknown');
Suggestions appreciated.
Thanks
EDIT
My checking for 'undefined' isn't actually what I use. It just came out of my head when asking the question. lol
But I was wondering, could I just wrap in a try/catch and throw default if exception?
function(obj, default) {
try {
if(obj != null) {
return obj;
} else {
return default;
}
} catch(ex) {
return default;
}
}
Also, thanks to Shusi for pointing the redundant vars.
You can do it with a helper function. If I understand your problem correctly, your objects may have arbitrary deep objects, and you want to access these arbitrary nested properties without cluttering your code. I built a
Nested
function which lets youget()
arbitrary properties if they are set, or a default if they are not.You can then write code like this
As you can see, it's not so much more typing. Sure, it doesn't feel like regular Javascript... Here is the fiddle.
following function will take string as parameter and return object if exist
Note: You must not use var while assigning properties to object eg.
var obj.computers.favorite
is SYNTAX error.Unfortunately, there's not a super easy way to get around this, but you don't need to check for both null and undefined. Because null and undefined are both falsey, you can just do:
It doesn't actually get around what your complaint is, but it's less painful than what you'd think.
You can also do this with JavaScript ES5
reduce
function :It makes a array out of the member string, then the accumulator progressively traverse within the object as the members are reduced.
You can use it like this, even with arrays :
There is a codepen to safely traverse js object
You can really write:
I wrote this to help you deal with one of your questions: "I need to see if obj.computers.favorite has been set".
Test-code: