UnderscoreJS:有没有办法递归迭代JSON结构?

Guy*_*Guy 4 javascript underscore.js lodash

 var updateIconPathRecorsive = function (item) {
          if (item.iconSrc) {
              item.iconSrcFullpath = 'some value..';
          }

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

      updateIconPathRecorsive(json);
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法不使用功能?我不想将函数从调用中移开,因为它就像一个复杂的函数.我可能希望能够写下以下内容:

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

Ber*_*rgi 6

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

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

但你的代码片段也很好,不会在IE中引起问题.

下划线没有递归包装函数,也没有Y-combinator.但如果你愿意,你当然可以轻松自己创建一个:

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