test the existence of property in a deep object structure

前端 未结 6 1348
悲&欢浪女
悲&欢浪女 2021-01-11 23:13

In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a

6条回答
  •  余生分开走
    2021-01-11 23:58

    /*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

    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).

    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: Add a method to Object primative, but not have it come up as a property

    Here is my code for that:

    Object.defineProperty(Object.prototype, 'descend', {
        value: function(){
            var keys = arguments;
            var cur = this;
            for(var i=0; i

提交回复
热议问题