Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Regex从字符串中获取对象参数,并从JSON/Js对象中获取这些参数的值_Javascript_Regex_String - Fatal编程技术网

Javascript Regex从字符串中获取对象参数,并从JSON/Js对象中获取这些参数的值

Javascript Regex从字符串中获取对象参数,并从JSON/Js对象中获取这些参数的值,javascript,regex,string,Javascript,Regex,String,我有两个字符串和一个Js对象 var strArr = '$PARAMS["version"]["config"]$'; var strObj = "$PARAMS.version.config$; 和JS对象 var obj = { "version": { "config": { "prod": "stackoverflow" } } } 字符串可以是strArr或strObj,我试图获取一个正则表达式,从这两个字符

我有两个字符串和一个Js对象

var strArr = '$PARAMS["version"]["config"]$';
var strObj = "$PARAMS.version.config$;
和JS对象

var obj = {
    "version": {
        "config": {
            "prod": "stackoverflow"
        }
    }
}
字符串可以是strArr或strObj,我试图获取一个正则表达式,从这两个字符串中提取version和config(等等),并从Js obj中获取相同的值

例如:
obj[“版本”][“配置]

我可以为strArr解决这个问题,即“$PARAMS[“version”][“config”]$”,需要修改下面的getVal函数中的正则表达式,以获得strObj的工作状态

在下面的函数中,路径可以是strArr或strObj

function getVal(obj, path) => {
    let regex = /\["(.*?)"\]/mg;
    let m;

    while ((m = regex.exec(path)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }

        if(typeof obj[m[1]] !== 'undefined') obj = obj[m[1]];
        else return obj[m[1]];
    }
    return obj;
}

将正则表达式更改为/.([\w])|[“(.?)”]/mg 在函数中添加以下行修复了该问题 如果(对象类型[m[2]]!==“未定义”)对象=对象[m[2]];

最后一个函数看起来像

function getVal(obj, path) {
                    let regex = /\.([\w]*)|\["(.*?)"\]/mg;
                    // let regex = /\["(.*?)"\]/mg;
                    let m;
                    while ((m = regex.exec(path)) !== null) {
                        // This is necessary to avoid infinite loops with zero-width matches
                        if (m.index === regex.lastIndex) {
                            regex.lastIndex++;
                        }
                        if(typeof obj[m[1]] !== 'undefined') obj = obj[m[1]];
                        else if(typeof obj[m[2]] !== 'undefined') obj = obj[m[2]];
                        //TODO: Add logic to through error if the parameter is not found
                    }
                    return obj;
                }

到目前为止你试过什么