【问题标题】:UnderscoreJS: Is there a way to iterate a JSON structure recursively?UnderscoreJS:有没有办法递归地迭代 JSON 结构?
【发布时间】:2013-08-13 16:15:09
【问题描述】:
 var updateIconPathRecorsive = function (item) {
          if (item.iconSrc) {
              item.iconSrcFullpath = 'some value..';
          }

          _.each(item.items, updateIconPathRecorsive);
      };

      updateIconPathRecorsive(json);

有没有更好的不使用函数的方法? 我不想将函数从调用中移开,因为它就像一个复杂的 for。我可能希望能够在以下行中写一些东西:

   _.recursive(json, {children: 'items'}, function (item) {
      if (item.iconSrc) {
          item.iconSrcFullpath = 'some value..';
      }
   }); 

【问题讨论】:

  • 您需要在某个时候引用该函数。你的第一个代码 sn-p 对我来说很好。
  • 所以基本上你想要的是递归所有对象属性的迭代器?

标签: javascript underscore.js lodash


【解决方案1】:

您可以使用立即调用的命名函数表达式:

(function updateIconPathRecorsive(item) {
    if (item.iconSrc) {
        item.iconSrcFullpath = 'some value..';
    }
    _.each(item.items, updateIconPathRecorsive);
})(json);

但你的 sn-p 也很好,不会cause problems in IE

下划线没有递归包装函数,也没有提供Y-combinator。但如果你愿意,你当然可以轻松create one yourself

_.mixin({
    recursive: function(obj, opt, iterator) {
        function recurse(obj) {
            iterator(obj);
            _.each(obj[opt.children], recurse);
        }
        recurse(obj);
    }
});

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 2016-09-23
    • 2018-08-26
    • 2019-07-04
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多