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

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

    Here's how you can do that in lodash:

    _.mixin({
        'deepMapKeys': function (obj, fn) {
    
            var x = {};
    
            _.forOwn(obj, function(v, k) {
                if(_.isPlainObject(v))
                    v = _.deepMapKeys(v, fn);
                x[fn(v, k)] = v;
            });
    
            return x;
        }
    });
    

    and here's a more abstract mixin, that recursively applies any given mapper:

    _.mixin({
        deep: function (obj, mapper) {
            return mapper(_.mapValues(obj, function (v) {
                return _.isPlainObject(v) ? _.deep(v, mapper) : v;
            }));
        },
    });
    

    Usage (returns the same as above):

    obj = _.deep(obj, function(x) {
        return _.mapKeys(x, function (val, key) {
            return key + '_hi';
        });
    });
    

    Another option, with more elegant syntax:

    _.mixin({
        deeply: function (map) {
            return function(obj, fn) {
                return map(_.mapValues(obj, function (v) {
                    return _.isPlainObject(v) ? _.deeply(map)(v, fn) : v;
                }), fn);
            }
        },
    });
    
    
    obj = _.deeply(_.mapKeys)(obj, function (val, key) {
        return key + '_hi';
    });
    

提交回复
热议问题