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

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 the function? I do not want to push the function away from the call, because it is simply complicated. I probably want to write something in the following lines:

  _.recursive(json, {children: 'items'}, function (item) { if (item.iconSrc) { item.iconSrcFullpath = 'some value..'; } }); 
+4
source share
1 answer

You can use the immediately called function function expression:

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

But your snippet is also beautiful and will not cause problems in IE .

There is no recursive wrapper function to underline, and it does not provide a Y-combinator . But if you want, you can easily create it yourself :

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

Source: https://habr.com/ru/post/1496847/


All Articles