test the existence of property in a deep object structure

前端 未结 6 1296
悲&欢浪女
悲&欢浪女 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-12 00:10

    I use this simple function for playing around with deep object properties:

    getProperty = function(path) {
        try {
            return eval(path);
        }
        catch (e) {
            return undefined;
        }
    };
    

    Here's an example:

    var test = {a:{b:{c:"success!"}}};
    
    alert(getProperty('test.c.c'));
    // undefined
    
    alert(getProperty('test.a.b.c'));
    // success!
    

提交回复
热议问题