我需要在我的对象中查找并替换与正则表达式匹配的值(例如 **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) 的结构和找到的匹配项的位置会发生变化。
- > 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
所以... 这是我的递归解决方案,用于查找与所需正则表达式匹配的值
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;}))
关于javascript - 在多维javascript对象中递归查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473526/