Skip to content

Instantly share code, notes, and snippets.

@harish2704
Last active June 3, 2023 23:41
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save harish2704/d0ee530e6ee75bad6fd30c98e5ad9dab to your computer and use it in GitHub Desktop.
Save harish2704/d0ee530e6ee75bad6fd30c98e5ad9dab to your computer and use it in GitHub Desktop.
Simple lodash.get function in javascript
/* 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;
}
@romanown
Copy link

setProp is not work.

@andrewchilds
Copy link

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

@romanown
Copy link

many thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment