You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0 KiB

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