简体   繁体   中英

How do I easily get the value of a nested field in Javascript without null reference exceptions?

I've seen a lot of posts on using the in operator in Javascript to check if a field exists on an object or up the object's prototype chain, but I've seen none for going down the other way.

Let's say I have an object:

var obj = {
     myField
}

And myField is set to another object, with various fields on it:

obj.myField = {
     mySetting: true
}

If I want to reference mySetting , let's say in an if statement, I have to do something like this:

if (obj.myField && obj.myField.mySetting && obj.myField.mySetting === true)

If I use in , it is still clumsy:

if ("myField" in obj && "mySetting" in obj.myField && obj.myField.mySetting === true)

The following returns false:

if ("mySetting" in obj)

Is there some syntax I'm not aware of that can allow me to write a decent if statement here, returning false if it doesn't exist, or barring that, at least not throw an exception. I use jQuery, so a solution with that would be fine as well.

var a = { b: { c: { d: 10 } } };
var res = [ 'b', 'c', 'd' ].reduce(function(p, c) {
  return p ? p[c] : p;
}, a);

You could improve that with some syntactic sugar, I suppose:

function nested_get(obj, path) {
  return path.split('.').reduce(function(p,c){return p?p[c]:p;}, obj);
}

var obj = { some: { weird: { nested: 'thing' } } };
alert(nested_get(obj, 'some.weird.nested'));

You are checking for myfield instead of myField that is why you are getting it as false. Remember that JavaScript is case sensitive.

alert(("myField" in obj && "mySetting" in obj.myField && obj.myField.mySetting === true));

Working demo - http://jsfiddle.net/Yfuvu/

I'm not sure there's a nice way to describe a nested property, which you would of course need to do in order to directly check whether it exists or not. As an alternative, you might consider using an intermediate variable to stand in for the field you want to test:

var myField = obj.myField;
if (myField.mySetting && myField.mySetting === true) { /* do stuff */ }

Finally, it's worth at least mentioning the Object.hasOwnProperty method that you might use to check for the existence of a field. Rewriting the example above:

var myField = obj.myField;
if (myField.hasOwnProperty('mySetting') && myField.mySetting === true) { 
  /* do stuff */ 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM