Fork notice
This fork is a TypeScript implementation of dlv.
dlv(obj, keypath)
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
Why?
Smallest possible implementation: only 130 bytes.
You could write this yourself, but then you'd have to write tests.
Supports ES Modules, CommonJS and globals.
Installation
npm install --save dlv
Usage
delve(object, keypath, [default])
import delve from 'dlv';
let obj = {
a: {
b: {
c: 1,
d: undefined,
e: null
}
}
};
delve(obj, 'a.b.c') === 1;
delve(obj, ['a', 'b', 'c']) === 1;
delve(obj, 'a.b') === obj.a.b;
delve(obj, 'a.b.c.f') === undefined;
delve(obj, 'a.b.c.f', 'foo') === 'foo';
delve(obj, 'a.b.c.d', 'foo') === 'foo';
delve(obj, 'a.b.c.e', 'foo') === null;
delve(undefined, 'a.b.c') === undefined;
delve(undefined, 'a.b.c', 'foo') === 'foo';
delve(obj, undefined, 'foo') === 'foo';
Setter Counterparts
- dset by @lukeed is the spiritual "set" counterpart of
dlv
and very fast. - bury by @kalmbach does the opposite of
dlv
and is implemented in a very similar manner.
License
MIT