main
|
Last change
on this file was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago |
|
Initial commit
|
-
Property mode
set to
100644
|
|
File size:
1.4 KB
|
| Line | |
|---|
| 1 | # undefsafe
|
|---|
| 2 |
|
|---|
| 3 | Simple *function* for retrieving deep object properties without getting "Cannot read property 'X' of undefined"
|
|---|
| 4 |
|
|---|
| 5 | Can also be used to safely set deep values.
|
|---|
| 6 |
|
|---|
| 7 | ## Usage
|
|---|
| 8 |
|
|---|
| 9 | ```js
|
|---|
| 10 | var object = {
|
|---|
| 11 | a: {
|
|---|
| 12 | b: {
|
|---|
| 13 | c: 1,
|
|---|
| 14 | d: [1,2,3],
|
|---|
| 15 | e: 'remy'
|
|---|
| 16 | }
|
|---|
| 17 | }
|
|---|
| 18 | };
|
|---|
| 19 |
|
|---|
| 20 | console.log(undefsafe(object, 'a.b.e')); // "remy"
|
|---|
| 21 | console.log(undefsafe(object, 'a.b.not.found')); // undefined
|
|---|
| 22 | ```
|
|---|
| 23 |
|
|---|
| 24 | Demo: [https://jsbin.com/eroqame/3/edit?js,console](https://jsbin.com/eroqame/3/edit?js,console)
|
|---|
| 25 |
|
|---|
| 26 | ## Setting
|
|---|
| 27 |
|
|---|
| 28 | ```js
|
|---|
| 29 | var object = {
|
|---|
| 30 | a: {
|
|---|
| 31 | b: [1,2,3]
|
|---|
| 32 | }
|
|---|
| 33 | };
|
|---|
| 34 |
|
|---|
| 35 | // modified object
|
|---|
| 36 | var res = undefsafe(object, 'a.b.0', 10);
|
|---|
| 37 |
|
|---|
| 38 | console.log(object); // { a: { b: [10, 2, 3] } }
|
|---|
| 39 | console.log(res); // 1 - previous value
|
|---|
| 40 | ```
|
|---|
| 41 |
|
|---|
| 42 | ## Star rules in paths
|
|---|
| 43 |
|
|---|
| 44 | 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.
|
|---|
| 45 |
|
|---|
| 46 | 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:
|
|---|
| 47 |
|
|---|
| 48 | ```js
|
|---|
| 49 | const githubData = {
|
|---|
| 50 | commits: [{
|
|---|
| 51 | modified: [
|
|---|
| 52 | "one",
|
|---|
| 53 | "two"
|
|---|
| 54 | ]
|
|---|
| 55 | }, /* ... */ ]
|
|---|
| 56 | };
|
|---|
| 57 |
|
|---|
| 58 | // first modified file found in the first commit
|
|---|
| 59 | console.log(undefsafe(githubData, 'commits.*.modified.0'));
|
|---|
| 60 |
|
|---|
| 61 | // returns `two` or undefined if not found
|
|---|
| 62 | console.log(undefsafe(githubData, 'commits.*.modified.*', 'two'));
|
|---|
| 63 | ```
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.