【问题标题】:mootools javascript return Array.each() with recursionmootools javascript 使用递归返回 Array.each()
【发布时间】: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


【解决方案1】:

经过更多的调查和尝试,我和我的同事自己解决了这个问题,使用“for”循环而不是“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 }

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 2020-01-26
    • 2012-05-29
    • 2021-11-09
    • 2016-05-27
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多