source: node_modules/undefsafe/README.md@ 81bc7da

finki-main main
Last change on this file since 81bc7da was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

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