test the existence of property in a deep object structure

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

    Here's the one i have been using for a while

       var obj = { a: { b: [
                            { c: {d: 'XYZ'} }
                        ] } };
    
        // working
    
        obj.a.b[0].c.d = null;
        console.log('value:'+getProperty(obj, 'a.b[0].c.d', 'NOT-AVAILABLE')); // value:null
    
        obj.a.b[0].c.d = 'XYZ';
        console.log('value:'+getProperty(obj, 'a.b[0].c.d', 'NOT-AVAILABLE')); // value:XYZ
        console.log('value:'+getProperty(obj, 'a.b[0].c.d.k.sds', 'NOT-AVAILABLE')); // value:NOT-AVAILABLE
    
        obj.a.b[0].c = null;
        console.log('value:'+getProperty(obj, 'a.b[0].c.d', 'NOT-AVAILABLE'));  // value:NOT-AVAILABLE
    
    
        // will not work
        //console.log('v:'+getProperty(obj, 'a.b["0"].c.d'));
    

    Here's the function

    function getProperty(obj, str, defaultValue){
    
        var props = str.split('.').map(function(prop){
            var arrAccessRegEx = /(.*)\[(.*)\]/g;
            if (arrAccessRegEx.test(prop)){
                return prop.split(arrAccessRegEx).filter(function(ele){return ele!=''; });
            } else {
                var retArr = [];
                retArr.push(prop);
                return retArr
            };
        });
    
        //console.log(props);
    
        for(var i=0;i

提交回复
热议问题