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

前端 未结 5 645
刺人心
刺人心 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:24

    I've add a small improvement from Chris Jones's answer.

    Following code fix some unintended results of Array elements.

    _.mixin({
      deeply: function (map) {
        var 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);
        }
      },
    });
    

提交回复
热议问题