| 1 | # `dlv(obj, keypath)` [](https://npmjs.com/package/dlv) [](https://travis-ci.org/developit/dlv)
|
|---|
| 2 |
|
|---|
| 3 | > 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
|
|---|
| 4 |
|
|---|
| 5 |
|
|---|
| 6 | ### Why?
|
|---|
| 7 |
|
|---|
| 8 | Smallest possible implementation: only **130 bytes.**
|
|---|
| 9 |
|
|---|
| 10 | You could write this yourself, but then you'd have to write [tests].
|
|---|
| 11 |
|
|---|
| 12 | Supports ES Modules, CommonJS and globals.
|
|---|
| 13 |
|
|---|
| 14 |
|
|---|
| 15 | ### Installation
|
|---|
| 16 |
|
|---|
| 17 | `npm install --save dlv`
|
|---|
| 18 |
|
|---|
| 19 |
|
|---|
| 20 | ### Usage
|
|---|
| 21 |
|
|---|
| 22 | `delve(object, keypath, [default])`
|
|---|
| 23 |
|
|---|
| 24 | ```js
|
|---|
| 25 | import delve from 'dlv';
|
|---|
| 26 |
|
|---|
| 27 | let obj = {
|
|---|
| 28 | a: {
|
|---|
| 29 | b: {
|
|---|
| 30 | c: 1,
|
|---|
| 31 | d: undefined,
|
|---|
| 32 | e: null
|
|---|
| 33 | }
|
|---|
| 34 | }
|
|---|
| 35 | };
|
|---|
| 36 |
|
|---|
| 37 | //use string dot notation for keys
|
|---|
| 38 | delve(obj, 'a.b.c') === 1;
|
|---|
| 39 |
|
|---|
| 40 | //or use an array key
|
|---|
| 41 | delve(obj, ['a', 'b', 'c']) === 1;
|
|---|
| 42 |
|
|---|
| 43 | delve(obj, 'a.b') === obj.a.b;
|
|---|
| 44 |
|
|---|
| 45 | //returns undefined if the full key path does not exist and no default is specified
|
|---|
| 46 | delve(obj, 'a.b.f') === undefined;
|
|---|
| 47 |
|
|---|
| 48 | //optional third parameter for default if the full key in path is missing
|
|---|
| 49 | delve(obj, 'a.b.f', 'foo') === 'foo';
|
|---|
| 50 |
|
|---|
| 51 | //or if the key exists but the value is undefined
|
|---|
| 52 | delve(obj, 'a.b.d', 'foo') === 'foo';
|
|---|
| 53 |
|
|---|
| 54 | //Non-truthy defined values are still returned if they exist at the full keypath
|
|---|
| 55 | delve(obj, 'a.b.e', 'foo') === null;
|
|---|
| 56 |
|
|---|
| 57 | //undefined obj or key returns undefined, unless a default is supplied
|
|---|
| 58 | delve(undefined, 'a.b.c') === undefined;
|
|---|
| 59 | delve(undefined, 'a.b.c', 'foo') === 'foo';
|
|---|
| 60 | delve(obj, undefined, 'foo') === 'foo';
|
|---|
| 61 | ```
|
|---|
| 62 |
|
|---|
| 63 |
|
|---|
| 64 | ### Setter Counterparts
|
|---|
| 65 |
|
|---|
| 66 | - [dset](https://github.com/lukeed/dset) by [@lukeed](https://github.com/lukeed) is the spiritual "set" counterpart of `dlv` and very fast.
|
|---|
| 67 | - [bury](https://github.com/kalmbach/bury) by [@kalmbach](https://github.com/kalmbach) does the opposite of `dlv` and is implemented in a very similar manner.
|
|---|
| 68 |
|
|---|
| 69 |
|
|---|
| 70 | ### License
|
|---|
| 71 |
|
|---|
| 72 | [MIT](https://oss.ninja/mit/developit/)
|
|---|
| 73 |
|
|---|
| 74 |
|
|---|
| 75 | [preact]: https://github.com/developit/preact
|
|---|
| 76 | [tests]: https://github.com/developit/dlv/blob/master/test.js
|
|---|