获取对象多层级属性值

在开发中,我们常遇到获取对象的多层级属性值,例如a.b.c.d这种,则不免会遇到其中一层已经为undefined而导致后面取值报错。所以不得不做一次校验,类似 a.b&&a.b.c&&a.b.c.d这样,层级越多判断也越多。es未来提议以这种形式替换:a.b?.c?.d,但目前还没有得到浏览器的支持。所以很有必要做一个工具方法来简化书写,这里抛砖引玉一下

function getValueByPath(obj,path){
        var reg=/(?:(?:^|\.)([^\.\[\]]+))|(?:\[([^\[\]]+)\])/g;
        var names=[];
        var name=null;
        while((name=reg.exec(path))!=null){
            names.push(name[1] || name[2]);
        }
        var o=obj;
        for(var i=0;i<names.length;i++){
            o=o[names[i]];
            if(o === undefined){
                return undefined;
            }
        }
        return o;
    }
    var obj={
        a:{
            b:{
                c:[0,1,2,[3,{'a.b':'x'}]]
            }
        }
    }
    console.log(getValueByPath(obj,'a.b.c[3][1][a.c][1]'));
    console.log(getValueByPath(obj,'a.b.c[3][1][a.b]'));

    function getValueByPath2(obj,path) {
        try{
            var fun=new Function('','return obj'+path);
            return fun();
        }catch(e){
            return undefined;
        }
    }
    console.log(getValueByPath2(obj,'.a.b.c[3][1]["a.c"][1]'));
    console.log(getValueByPath2(obj,'.a.b.c[3][1]["a.b"]'));

猜你喜欢

转载自blog.csdn.net/zzgzzg00/article/details/79357221
今日推荐