获取对象指定路径的值

function getPropByPath(obj,path,strict){    
    let tempObj=obj;
    path=path.replace(/\[(\w+)\]/g,'.$1');
    path=path.replace(/^\./,'')
    let keyArr=path.split('.')
    let i=0;
    for(let len=keyArr.length;i<len-1;++i){
        if(!tempObj&&!strict)break;
        let key=keyArr[i]
        if(key in tempObj){
            tempObj=tempObj[key]
        }else{
            if(strict){
                throw new Error('please transfer a valid prop path to form item!')
            }
            break;
        }

    }
    return {
        o:tempObj,
        k:keyArr[i],
        v:tempObj?tempObj[keyArr[i]]:null
    }
}
let obj={name:{cc:{bb:1}}}
console.log(getPropByPath(obj,'name.cc.bb'));

  

posted @ 2021-12-21 11:32  7c89  阅读(81)  评论(0编辑  收藏  举报