Safely get a dot-notated path within a nested object, with ability to return a default if the full key path does not exist or the value is undefined
Smallest possible implementation: only 120 bytes.
You could write this yourself, but then you'd have to write tests.
Supports ES Modules, CommonJS and globals.
npm install --save dlv
delve(object, keypath, [default])
importdelvefrom'dlv';letobj={a: {b: {c: 1,d: undefined,e: null}}};//use string dot notation for keysdelve(obj,'a.b.c')===1;//or use an array keydelve(obj,['a','b','c'])===1;delve(obj,'a.b')===obj.a.b;//returns undefined if the full key path does not exist and no default is specifieddelve(obj,'a.b.f')===undefined;//optional third parameter for default if the full key in path is missingdelve(obj,'a.b.f','foo')==='foo';//or if the key exists but the value is undefineddelve(obj,'a.b.d','foo')==='foo';//Non-truthy defined values are still returned if they exist at the full keypathdelve(obj,'a.b.e','foo')===null;//undefined obj or key returns undefined, unless a default is supplieddelve(undefined,'a.b.c')===undefined;delve(undefined,'a.b.c','foo')==='foo';delve(obj,undefined,'foo')==='foo';