Created
October 22, 2017 15:24
-
-
Save hieu292/2ab2303294ebd22a13f211b7990a892d to your computer and use it in GitHub Desktop.
deeply map object keys with JavaScript (lodash)
https://stackoverflow.com/questions/35055731/how-to-deeply-map-object-keys-with-javascript-lodash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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; | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.mixin({ | |
deep: function (obj, mapper) { | |
return mapper(_.mapValues(obj, function (v) { | |
return _.isPlainObject(v) ? _.deep(v, mapper) : v; | |
})); | |
}, | |
}); | |
obj = _.deep(obj, function(x) { | |
return _.mapKeys(x, function (val, key) { | |
return key + '_hi'; | |
}); | |
}); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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'; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var obj = { a: 2, b: { c: 2, d: { a: 3 } } }; | |
_.deepMapKeys(obj, function (val, key) { | |
return val + '_hi'; | |
}); | |
// => { a_hi: 2, b_hi: { c_hi: 2, d_hi: { a_hi: 3 } } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment