Created
March 22, 2017 13:17
-
-
Save zambon/8b2d207bd21cf4fcd47b96cd6d7f99c2 to your computer and use it in GitHub Desktop.
Deeply iterate in objects with Lodash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.mixin({ | |
deeply: map => | |
(obj, fn) => | |
map(_.mapValues(obj, (v) => { | |
if (_.isPlainObject(v)) { | |
return _.deeply(map)(v, fn); | |
} else if (_.isArray(v)) { | |
return _.map(v, item => _.deeply(map)(item, fn)); | |
} | |
return v; | |
}), fn), | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.mixin({ | |
deeply: function(map) { | |
return function(obj, fn) { | |
return map(_.mapValues(obj, function(v) { | |
if (_.isPlainObject(v)) { | |
return _.deeply(map)(v, fn); | |
} else if (_.isArray(v)) { | |
return _.map(v, item => _.deeply(map)(item, fn)); | |
} | |
return v; | |
}), fn); | |
} | |
}, | |
}); |
This incorrectly converts Arrays from [0, 1, 2]
into { '0': undefined, '1': undefined, '2': undefined }
Final working version:
// <https://stackoverflow.com/a/41978063>
_.mixin({
deeply(map) {
// <https://stackoverflow.com/a/48032359>
const deeplyArray = function (obj, fn) {
return obj.map(function (x) {
return _.isPlainObject(x) ? _.deeply(map)(x, fn) : x;
});
};
return function (obj, fn) {
if (_.isArray(obj)) return deeplyArray(obj, fn);
return map(
_.mapValues(obj, function (v) {
return _.isPlainObject(v)
? _.deeply(map)(v, fn)
: _.isArray(v)
? deeplyArray(v, fn)
: v;
}),
fn
);
};
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 8 (on both) should be
return v.map((item) => deeply(map)(item, fn))