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
1 Answer
Reset to default 6You 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);
}
});