How to deeply map object keys with JavaScript (lodash)?

前端 未结 5 794
刺人心
刺人心 2021-02-02 12:48

https://lodash.com/docs#mapKeys

Is it possible to map an Object\'s keys deeply using Lodash? If not, is there another library providing this functionality (if grouped wi

5条回答
  •  天命终不由人
    2021-02-02 13:19

    In extention of georg's answer, here's what I'm using. This extended mixin adds the ability to map arrays of objects within the object too, a simple but important change.

    _.mixin({
        deeply: function (map) {
          return function (obj, fn) {
            return map(_.mapValues(obj, function (v) {
              return _.isPlainObject(v) ? _.deeply(map)(v, fn) : _.isArray(v) ? v.map(function(x) {
                return _.deeply(map)(x, fn);
              }) : v;
            }), fn);
          }
        },
      });
    

提交回复
热议问题