Skip to content

Instantly share code, notes, and snippets.

@zambon
Created March 22, 2017 13:17
Show Gist options
  • Save zambon/8b2d207bd21cf4fcd47b96cd6d7f99c2 to your computer and use it in GitHub Desktop.
Save zambon/8b2d207bd21cf4fcd47b96cd6d7f99c2 to your computer and use it in GitHub Desktop.
Deeply iterate in objects with Lodash
_.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),
});
_.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);
}
},
});
@daviestar
Copy link

line 8 (on both) should be return v.map((item) => deeply(map)(item, fn))

@titanism
Copy link

This incorrectly converts Arrays from [0, 1, 2] into { '0': undefined, '1': undefined, '2': undefined }

@titanism
Copy link

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