我想遍历一个JSON对象树,但找不到任何库.这似乎并不困难,但感觉就像重新发明轮子一样.
在XML中,有很多教程展示了如何使用DOM遍历XML树:(
我正在尝试遍历嵌套对象以检索由字符串标识的特定对象.在下面的示例对象中,标识符字符串是"label"属性.我无法绕过如何遍历树以返回适当的对象.任何帮助或建议将不胜感激.
var cars = {
label: 'Autos',
subs: [
{
label: 'SUVs',
subs: []
},
{
label: 'Trucks',
subs: [
{
label: '2 Wheel Drive',
subs: []
},
{
label: '4 Wheel Drive',
subs: [
{
label: 'Ford',
subs: []
},
{
label: 'Chevrolet',
subs: []
}
]
}
]
},
{
label: 'Sedan',
subs: []
}
]
}
Run Code Online (Sandbox Code Playgroud) 当它们匹配正则表达式(例如**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: []
}
Run Code Online (Sandbox Code Playgroud)
这个对象被传递到一个主函数中,该函数使用传入的对象构建一个 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, …Run Code Online (Sandbox Code Playgroud)