Created
March 3, 2021 03:32
-
-
Save jvinhit/33fb6d35cb8f7e600fea1442d3bab0cc to your computer and use it in GitHub Desktop.
get/ set nested object property via key (nested or no) funciton implement get/set of 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
/* Implementation of lodash.get function */ | |
function getProp( object, keys, defaultVal ){ | |
keys = Array.isArray( keys )? keys : keys.split('.'); | |
object = object[keys[0]]; | |
if( object && keys.length>1 ){ | |
return getProp( object, keys.slice(1) ); | |
} | |
return object === undefined? defaultVal : object; | |
} | |
/* Implementation of lodash.set function */ | |
function setProp( object, keys, val ){ | |
keys = Array.isArray( keys )? keys : keys.split('.'); | |
if( keys.length>1 ){ | |
object[keys[0]] = object[keys[0]] || {}; | |
return setProp( object[keys[0]], keys.slice(1), val ); | |
} | |
object[keys[0]] = val; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment