I need to find and replace values in my object when they match a regular expression (e.g. **myVar**); The object that I need to loop through is user defined and structure varies.
Here is an example object, shortened for simplicity.
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: []
}
This object is passed into a master function that builds a angularjs resource object using the passed in object.
Here is the structure I am using:
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() is based on the following questions/answers, but my case is different because the structure of the passed in object (var testObject) and the location of the found match will change.
- JSON Object array inside array find and replace in javascript
- How to iterate through all keys & values of nested object?
- Traverse all the Nodes of a JSON Object Tree with JavaScript
SO... Here is my recursive solution to find the values that match the desired regex
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;
}
This function successfully finds the values that match the regex, however, I can't seem to return the updated object without directly refrencing the structure of the testObject.
Here is a jsfiddle of the code above. http://jsfiddle.net/joshvito/2Lu4oexj/
My goal is to be able to search through the incoming object, find any values that match the regular expression, and change the value to the value defined in userVars (if the object value and userVar key match).