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.

пре 4 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # undefsafe
  2. Simple *function* for retrieving deep object properties without getting "Cannot read property 'X' of undefined"
  3. Can also be used to safely set deep values.
  4. ## Usage
  5. ```js
  6. var object = {
  7. a: {
  8. b: {
  9. c: 1,
  10. d: [1,2,3],
  11. e: 'remy'
  12. }
  13. }
  14. };
  15. console.log(undefsafe(object, 'a.b.e')); // "remy"
  16. console.log(undefsafe(object, 'a.b.not.found')); // undefined
  17. ```
  18. Demo: [https://jsbin.com/eroqame/3/edit?js,console](https://jsbin.com/eroqame/3/edit?js,console)
  19. ## Setting
  20. ```js
  21. var object = {
  22. a: {
  23. b: [1,2,3]
  24. }
  25. };
  26. // modified object
  27. var res = undefsafe(object, 'a.b.0', 10);
  28. console.log(object); // { a: { b: [10, 2, 3] } }
  29. console.log(res); // 1 - previous value
  30. ```
  31. ## Star rules in paths
  32. As of 1.2.0, `undefsafe` supports a `*` in the path if you want to search all of the properties (or array elements) for a particular element.
  33. The function will only return a single result, either the 3rd argument validation value, or the first positive match. For example, the following github data:
  34. ```js
  35. const githubData = {
  36. commits: [{
  37. modified: [
  38. "one",
  39. "two"
  40. ]
  41. }, /* ... */ ]
  42. };
  43. // first modified file found in the first commit
  44. console.log(undefsafe(githubData, 'commits.*.modified.0'));
  45. // returns `two` or undefined if not found
  46. console.log(undefsafe(githubData, 'commits.*.modified.*', 'two'));
  47. ```