opusdev/vector-similarity-api
1
1# undefsafe2 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## Usage8 9```js10var 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')); // undefined22```23 24Demo: [https://jsbin.com/eroqame/3/edit?js,console](https://jsbin.com/eroqame/3/edit?js,console)25 26## Setting27 28```js29var object = {30 a: {31 b: [1,2,3]32 }33};34 35// modified object36var res = undefsafe(object, 'a.b.0', 10);37 38console.log(object); // { a: { b: [10, 2, 3] } }39console.log(res); // 1 - previous value40```41 42## Star rules in paths43 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```js49const githubData = {50 commits: [{51 modified: [52 "one",53 "two"54 ]55 }, /* ... */ ]56 };57 58// first modified file found in the first commit59console.log(undefsafe(githubData, 'commits.*.modified.0'));60 61// returns `two` or undefined if not found62console.log(undefsafe(githubData, 'commits.*.modified.*', 'two'));63```64 