【发布时间】:2015-02-24 03:26:45
【问题描述】:
我有一个 JSON 对象数组,其中这些对象也可能是 JSON 对象数组。现在,我需要动态地在其中找到一个值,因为数组中的对象的 no: 将不相同,.例如,
[
{
"Plan": {
"Node Type": "CTE Scan",
"CTE Name": "tab",
"Alias": "tab",
"Startup Cost": 756.66,
"Total Cost": 761.16,
"Plan Rows": 67,
"Plan Width": 12,
"Filter": "(sum > 10000)",
"Plans": [
{
"Node Type": "Aggregate",
"Strategy": "Sorted",
"Parent Relationship": "InitPlan",
"Subplan Name": "CTE tab",
"Startup Cost": 471.70,
"Total Cost": 756.66,
"Plan Rows": 200,
"Plan Width": 8,
"Plans": [
{
"Node Type": "Merge Join",
"Parent Relationship": "Outer",
"Join Type": "Inner",
"Startup Cost": 471.70,
"Total Cost": 684.82,
"Plan Rows": 13968,
"Plan Width": 8,
"Merge Cond": "(p.pr_id = ep.pr_id)",
"Plans": [
{
"Node Type": "Sort",
"Parent Relationship": "Outer",
"Startup Cost": 51.37,
"Total Cost": 53.17,
"Plan Rows": 720,
"Plan Width": 4,
"Sort Key": ["p.pr_id"],
"Plans": [
{
"Node Type": "Seq Scan",
"Parent Relationship": "Outer",
"Relation Name": "product",
"Alias": "p",
"Startup Cost": 0.00,
"Total Cost": 17.20,
"Plan Rows": 720,
"Plan Width": 4
}
]
},
{
"Node Type": "Sort",
"Parent Relationship": "Inner",
"Startup Cost": 420.33,
"Total Cost": 430.03,
"Plan Rows": 3880,
"Plan Width": 8,
"Sort Key": ["ep.pr_id"],
"Plans": [
{
"Node Type": "Hash Join",
"Parent Relationship": "Outer",
"Join Type": "Inner",
"Startup Cost": 19.00,
"Total Cost": 189.05,
"Plan Rows": 3880,
"Plan Width": 8,
"Hash Cond": "(ep.emp_id = e.emp_id)",
"Plans": [
{
"Node Type": "Seq Scan",
"Parent Relationship": "Outer",
"Relation Name": "employee_vs_product",
"Alias": "ep",
"Startup Cost": 0.00,
"Total Cost": 29.40,
"Plan Rows": 1940,
"Plan Width": 12
},
{
"Node Type": "Hash",
"Parent Relationship": "Inner",
"Startup Cost": 14.00,
"Total Cost": 14.00,
"Plan Rows": 400,
"Plan Width": 12,
"Plans": [
{
"Node Type": "Seq Scan",
"Parent Relationship": "Outer",
"Relation Name": "employee",
"Alias": "e",
"Startup Cost": 0.00,
"Total Cost": 14.00,
"Plan Rows": 400,
"Plan Width": 12
}
]
}
]
}
]
}
]
}
]
}
]
}
}
]
在这里,我需要找到键为“Relaion Name”的值......该键有三个值,我们不知道是否:其中存在的对象......所以我需要一个解决方案来找到具有该键的值是动态的。
我试图编写一个递归函数,但我没有成功。如果你知道的话,请帮助我。
我试过的递归函数:
var result1=searchInPlan(jsonarray[0].Plan);
function searchInPlan(node)
{
var result='';
{
if(node.Plans == undefined)
{
if(node["Relation Type"] != undefined)
result += node["Relation Name"];
return result;
}
else
{
return result+searchInPlans(node.Plans);
}
}
}
function searchInPlans(nodes)
{
console.log("bollo",nodes);
var result = '';
for(j=0;j<nodes.length;j++)
{
result += searchInPlan(nodes[j]);
}
return result;
}
它正在工作,但我只能使用该键获得第一个值...我需要该键的所有值..帮助我..
【问题讨论】:
-
使用
underscore库,就像linqforjavascript -
分享你尝试过的递归函数...人们会更愿意回应,他们也可能会提出替代方案。
-
@JoelGregory...我添加了我尝试过的递归函数..