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.

103 lines
1.7 KiB

4 years ago
  1. # dot-prop [![Build Status](https://travis-ci.org/sindresorhus/dot-prop.svg?branch=master)](https://travis-ci.org/sindresorhus/dot-prop)
  2. > Get, set, or delete a property from a nested object using a dot path
  3. ## Install
  4. ```
  5. $ npm install --save dot-prop
  6. ```
  7. ## Usage
  8. ```js
  9. const dotProp = require('dot-prop');
  10. // getter
  11. dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
  12. //=> 'unicorn'
  13. dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
  14. //=> undefined
  15. dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value');
  16. //=> 'default value'
  17. dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
  18. //=> 'unicorn'
  19. // setter
  20. const obj = {foo: {bar: 'a'}};
  21. dotProp.set(obj, 'foo.bar', 'b');
  22. console.log(obj);
  23. //=> {foo: {bar: 'b'}}
  24. const foo = dotProp.set({}, 'foo.bar', 'c');
  25. console.log(foo);
  26. //=> {foo: {bar: 'c'}}
  27. dotProp.set(obj, 'foo.baz', 'x');
  28. console.log(obj);
  29. //=> {foo: {bar: 'b', baz: 'x'}}
  30. // has
  31. dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar');
  32. //=> true
  33. // deleter
  34. const obj = {foo: {bar: 'a'}};
  35. dotProp.delete(obj, 'foo.bar');
  36. console.log(obj);
  37. //=> {foo: {}}
  38. obj.foo.bar = {x: 'y', y: 'x'};
  39. dotProp.delete(obj, 'foo.bar.x');
  40. console.log(obj);
  41. //=> {foo: {bar: {y: 'x'}}}
  42. ```
  43. ## API
  44. ### get(obj, path, [defaultValue])
  45. ### set(obj, path, value)
  46. Returns the object.
  47. ### has(obj, path)
  48. ### delete(obj, path)
  49. #### obj
  50. Type: `Object`
  51. Object to get, set, or delete the `path` value.
  52. #### path
  53. Type: `string`
  54. Path of the property in the object, using `.` to separate each nested key.
  55. Use `\\.` if you have a `.` in the key.
  56. #### value
  57. Type: `any`
  58. Value to set at `path`.
  59. #### defaultValue
  60. Type: `any`
  61. Default value.
  62. ## License
  63. MIT © [Sindre Sorhus](https://sindresorhus.com)