Last active
February 21, 2025 08:14
-
-
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; | |
} |
setProp is not work.
I created a fork of this version that includes tests, handles falsey values (including undefined
), and handles objects-inside-arrays (i.e. '[0].id'
) as well as arrays-inside-objects (i.e. 'a.b[0].c'
):
https://gist.github.com/andrewchilds/30a7fb18981d413260c7a36428ed13da
many thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution fixed for me a problem: Empty string counts as undefined.
I'd like the empty string back. It's not the same (for me).
I'm talking about the version without default value.