recursive js object replacement
by Josh Vito
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
JavaScript
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: []
};
function replaceVars(objSource, objReplacer){
var pattern = replaceVars.pattern;
if(typeof objSource === "object" ){
if(objSource === null) return null;
if(objSource instanceof Array){
for(var i = 0; i < objSource.length; i++){
objSource[i] = replaceVars(objSource[i], objReplacer);
}
}else{
for(var property in objSource){
objSource[property] = replaceVars(objSource[property], objReplacer);
}
}
return objSource;
}
if(typeof objSource === "string"){
return objSource.replace(pattern, function(finded, varName){
return varName in objReplacer ? objReplacer[varName] : finded;
});
}
return objSource;
}
replaceVars.pattern = /\*\*([0-9a-z_$]{1,})\*\*/gi;
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
//called with every property and it's value
function travelUniverse(collection){
_.forOwn(collection, function(n, key) {
if (n !== null && typeof(n) === "object") {
travelUniverse(n);
}
else {
if (pattern.test(n)) { //check the regex
...