UnderscoreJS: Is there a way to iterate a JSON structure recursively?

javascript, lodash, underscore.js

Solution

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-combinator 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);
    }
});

Problem

``` 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..'; } }); ```

Original source