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
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';
});