jos*_*ito 1 javascript json angularjs lodash
当它们匹配正则表达式(例如**myVar**)时,我需要查找和替换对象中的值;我需要循环的对象是用户定义的,结构各不相同。
这是一个示例对象,为简单起见进行了缩短。
var testObject = {
    name: "/pricing-setups/{folderId}", 
    method: "POST", 
    endpoint: "/pricing-setups/:folderId", 
    functionName: "create",
    Consumes: null,
    filename: "apicontracts/pricingsetups/PricingSetupServiceProxy.java",
    pathParam: [
        {$$hashKey: "06S",
          key: "folderId",
          value: "**myVar**"}
    ],
    queryParam: [],
    request_payload: "{'title':'EnterAname'}",
    returnList: []
}
这个对象被传递到一个主函数中,该函数使用传入的对象构建一个 angularjs 资源对象。
这是我正在使用的结构:
function getTestResult(dataSource, options) {
      //input into the service should be api obj and selected environment obj
      //extend the passed object with options if passed
      var opts = $.extend({}, dataSource, options);
      //swap the {param} syntax for :param in opts.endpoint
      opts.endpoint = opts.endpoint.replace(/\}/g, "").replace(/\{/g, ":");
      //replace any defined vars passed in from scenario via scenario.userVar
      opts = replaceUserVars(opts, {"myVar": "C=1000=Corporate"});
    //MORE CODE STUFF
    // ...
    // ...
}
replaceUserVars() 基于以下问题/答案,但我的情况不同,因为传入的对象 (var testObject) 的结构和找到的匹配项的位置会发生变化。
所以......这是我的递归解决方案,用于查找与所需正则表达式匹配的值
function replaceUserVars(api, uvars) {
      if (!uvars) {
        return api;
      }
      var pattern =  new RegExp("\\*\\*\\w*\\*\\*", "g");//match **myVar**
      //check the api params for a match to regex
      // and if we find a match, replace the string with the userVar[regex match].value
      function warpSpeedAhead(collection) {
        _.find(collection, function (obj) { //find obj in api
          if (obj !== null && typeof(obj) === "object") {
            warpSpeedAhead(obj);
          }
          else {
            if (pattern.test(obj)) { //check the regex
              var sanitVar = obj.replace(/\*/g, ""); //remove the *
              if (uvars[sanitVar]) {
                console.log("found one");
                obj = uvars[sanitVar];
                //should be equivalent to 
                //api.pathParam[0][key] = uvars[sanitVar]; //works in this case ONLY
              }
            }
          }
        });
      }
      warpSpeedAhead(api);
      return api;
    }
此函数成功找到与正则表达式匹配的值,但是,如果不直接引用 testObject 的结构,我似乎无法返回更新的对象。
这是上面代码的jsfiddle。http://jsfiddle.net/joshvito/2Lu4oexj/
我的目标是能够搜索传入的对象,找到与正则表达式匹配的任何值,并将值更改为 userVars 中定义的值(如果对象值和 userVar 键匹配)。
如何 JSON.stringify 并替换为字符串并返回到 JSON?
JSON.parse(JSON.stringify(testObject).replace(/\*\*([^*]+)\*\*/g,function($0,$1){return uvars[$1]||$0;}))
| 归档时间: | 
 | 
| 查看次数: | 5533 次 | 
| 最近记录: |