我有一个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“占位符-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",
...
},
}发布于 2016-09-20 15:02:03
经过更多的调查和尝试,我的同事和我自己解决了这个问题,使用了"for"-loop而不是"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 return obj;
12 }
13 if (obj.children === null || obj.children === undefined) {
14 return false;
15 }
16 for (var i = 0; i < obj.children.length; i++) {
17 var ret_val = Template.check_for_id_equality(obj.children[i], id);
18 if (ret_val !== false) {
19 return ret_val;
20 }
21 }
22 return false;
23 }https://stackoverflow.com/questions/39590150
复制相似问题