【发布时间】:2017-01-28 03:29:33
【问题描述】:
我有一个 JSON 对象,我想要实现的是,我可以通过 id 在对象中搜索 child_objects。我正在使用Array.each() 和一个递归函数,如下所示:
1 Template.get_object_attributes_by_id = function(id, template)
2 {
3 var template_obj = JSON.parse(template);
4 console.log(Template.check_for_id_equality(template_obj, id);
5 return Template.check_for_id_equality(template_obj, id);
6 }
7
8 Template.check_for_id_equality = function(obj, id)
9 {
10 if (obj.attrs.id !== id) {
11 if (obj.children === null || obj.children === undefined) {
12 return;
13 }
14 Array.each(obj.children, function(obj_child) {
15 return Template.check_for_id_equality(obj_child, id);
16 });
17 }
18 else {
19 console.log(obj);
20 return obj;
21 }
22 }
第19行的输出是调用Template.get_object_attributes_by_id(id, template)后正确的对象,但是第4行的输出是undefined。
似乎Array.each()“忽略”了回报并继续前进。所以现在我的问题是,如何正确返回对象,这样我才能在函数get_object_attributes_by_id()中得到它。
更新:
输入(模板)是一个 JSON 对象,如下所示,例如,我在其中搜索 id “placeholder-2”。这只是一个例子,所以请不要寻找缺少的括号或类似的东西,因为我使用的真实 JSON 对象显然是有效的。
{
"className":"Stage",
"attrs":{
"width":1337,
"height":4711
},
"children":[{
"className":"Layer",
"id":"placeholder-layer",
"attrs":{
"width":1337,
"height": 4711
},
"children":[{
"className":"Text",
"id":"placeholder-1",
"attrs":{
"fontsize":42,
"color":"black",
...
}
},
{
"className":"Text",
"id":"placeholder-2",
"attrs":{
"fontsize":37,
"color":"red",
...
}
},
...
]
}]
}
这将是预期的输出:
{
"className":"Text",
"id":"placeholder-2",
"attrs":{
"fontsize":37,
"color":"red",
...
},
}
【问题讨论】:
-
你查看 MooTools 的Object.subset了吗?如果这不是您想要的,您能否提供一个您想要实现的输入和输出的示例?
-
@Sergio 不幸的是,
Object.subset不是我需要的。我已经用示例输入和预期输出更新了问题。
标签: javascript arrays json recursion mootools