最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - UnderscoreJS: Is there a way to iterate a JSON structure recursively? - Stack Overflow

programmeradmin0浏览0评论
 var updateIconPathRecorsive = function (item) {
          if (item.iconSrc) {
              item.iconSrcFullpath = 'some value..';
          }

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

      updateIconPathRecorsive(json);

Is there a better way that does not use a function? I don't want to move the function away from the invocation because it is just like a sophisticated for. I'd probably want to be able to write something in the lines of:

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

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

      updateIconPathRecorsive(json);

Is there a better way that does not use a function? I don't want to move the function away from the invocation because it is just like a sophisticated for. I'd probably want to be able to write something in the lines of:

   _.recursive(json, {children: 'items'}, function (item) {
      if (item.iconSrc) {
          item.iconSrcFullpath = 'some value..';
      }
   }); 
Share Improve this question edited Aug 14, 2013 at 11:50 Guy asked Aug 13, 2013 at 16:15 GuyGuy 13.4k17 gold badges89 silver badges129 bronze badges 2
  • You need to reference the function at some point. Your first code snippet looks fine to me. – Halcyon Commented Aug 13, 2013 at 16:18
  • So basically what you want is an iterator on all object properties recursively? – Benjamin Gruenbaum Commented Aug 13, 2013 at 16:20
Add a ment  | 

1 Answer 1

Reset to default 6

You can use an immediately-invoked named function expression:

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

But your snippet is fine as well and will not cause problems in IE.

There is no recursive wrapper function for underscore, and it doesn't provide a Y-binator either. But if you want, you can easily create one yourself of course:

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

评论列表(0)

  1. 暂无评论