Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>/*decend through an object tree to a specified node, and return it. If node is unreachable, return undefined. This should also work with arrays in the tree. Examples: var test1 = {a:{b:{c:{d:1}}}}; console.log(objectDesend(test1, 'a', 'b', 'c', 'd')); var test2 = {a:{b:{c:1}}}; //will fail to reach d console.log(objectDesend(test2, 'a', 'b', 'c', 'd')); */ var objectDescend = function(){ var obj = arguments[0]; var keys = arguments; var cur = obj; for(var i=1; i&lt;keys.length; i++){ var key = keys[i]; var cur = cur[key]; if(typeof(cur)=='undefined') return cur; } return cur; } var test1 = {a:{b:{c:{d:1}}}}; console.log(objectDescend(test1, 'a', 'b', 'c', 'd')); var test2 = {a:{b:{c:1}}}; console.log(objectDescend(test2, 'a', 'b', 'c', 'd')); </code></pre> <p>So this will return either the value you are looking for, or undefined since that value doesn't exist. It won't return false, as that may actually be the value you are looking for (d:false). </p> <p>In my code base, I add Object.prototype.descend, so I can do test1.descend('a', 'b', 'c', 'd'). This will only work in ECMAScript 5 (IE>=9) since you need to make it so your function doesn't appear in enumerations. For more info: <a href="https://stackoverflow.com/questions/6642231/add-a-method-to-object-primative-but-not-have-it-come-up-as-a-property">Add a method to Object primative, but not have it come up as a property</a></p> <p>Here is my code for that:</p> <pre><code>Object.defineProperty(Object.prototype, 'descend', { value: function(){ var keys = arguments; var cur = this; for(var i=0; i&lt;keys.length; i++){ var key = keys[i]; var cur = cur[key]; if(typeof(cur)=='undefined') return cur; } return cur; } }); var test1 = {a:{b:{c:{d:false}}}}; //this will return false, which is the value of d console.log(test1.descend('a', 'b', 'c', 'd')); var test2 = {a:{b:{c:1}}}; //undefined since we can't reach d. console.log(test2.descend(test2, 'a', 'b', 'c', 'd')); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload