test the existence of property in a deep object structure

前端 未结 6 1344
悲&欢浪女
悲&欢浪女 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:52

    There are probably 3-4 different questions along this vein, and four times as many answers. None of them really satisfied me, so I made my own, and I'll share it.

    This function is called "deepGet".

    Example:

    deepGet(mySampleData, "foo.bar[2].baz", null);

    Here is the full code:

    function deepGet (obj, path, defaultValue) {
    
        // Split the path into components
        var a = path.split('.');
    
        // If we have just one component left, note that for later.
        var last = (a.length) === 1;
    
        // See if the next item is an array with an index
        var myregexp = /([a-zA-Z]+)(\[(\d+)\])+/; // matches:  item[0]
        var match = myregexp.exec(a[0]);
    
        // Get the next item
        var next;
        if (match !== null) {
            next = obj[match[1]];
            if (next !== undefined) {
                next = next[match[3]];
            }
        } else {
            next = obj[a[0]];
        }
    
        if (next === undefined || next === null) {
            // If we don't have what we want, return the default value
            return defaultValue;
        } else {
            if (last) {
                // If it's the last item in the path, return it
                return next; 
            } else { 
                // If we have more items in the path to go, recurse
                return deepGet (next, a.slice(1).join("."), defaultValue); 
            }
        }
    }
    

    Here is a jsFiddle: http://jsfiddle.net/7quzmjh8/2/

    I was inspired by these two things:

    http://designpepper.com/blog/drips/making-deep-property-access-safe-in-javascript.html http://jsfiddle.net/wxrzM/1/

    Hopefully this is useful to someone out there :)

提交回复
热议问题