Last active
June 3, 2023 23:41
-
-
Save harish2704/d0ee530e6ee75bad6fd30c98e5ad9dab to your computer and use it in GitHub Desktop.
Simple lodash.get function in javascript
This file contains 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
many thanks