diff --git a/README.md b/README.md index 2f07103..a39718b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_659 TILs and counting..._ +_660 TILs and counting..._ --- @@ -251,6 +251,7 @@ _659 TILs and counting..._ - [Numbers Are Empty](javascript/numbers-are-empty.md) - [Object Initialization With Shorthand Property Names](javascript/object-initialization-with-shorthand-property-names.md) - [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md) +- [Reach Into An Object For Nested Data With Get](javascript/reach-into-an-object-for-nested-data-with-get.md) - [Render An Array Of Elements With React 16](javascript/render-an-array-of-elements-with-react-16.md) - [Running ES6 Specs With Mocha](javascript/running-es6-specs-with-mocha.md) - [Scoping Variables With A Block Statement](javascript/scoping-variables-with-a-block-statement.md) diff --git a/javascript/reach-into-an-object-for-nested-data-with-get.md b/javascript/reach-into-an-object-for-nested-data-with-get.md new file mode 100644 index 0000000..59e7ec2 --- /dev/null +++ b/javascript/reach-into-an-object-for-nested-data-with-get.md @@ -0,0 +1,35 @@ +# Reach Into An Object For Nested Data With Get + +Among the many [lodash](https://lodash.com/) utilities is +[`_.get`](https://lodash.com/docs/4.17.5#get) for getting data from nested +objects. You can specify where to reach into the nested data of an object +using a _path_. + +Consider the following awkwardly nested object: + +```javascript +const resp = { + error: { + errors: [ + { message: "Something went wrong" }, + ], + }, +}; +``` + +Here is how we might reach into this with vanilla JavaScript: + +```javascript +resp.error.errors[0].message; +``` + +Reaching into this for the `message` value is tricky because as soon as the +`resp` object contains differently nested data, an error is likely to be +thrown. We can simultaneously avoid a bunch of exception handling logic and +provide a default value with the `_.get` function: + +```javascript +_.get(resp, 'resp.error.errors[0].message', 'Default error message'); +``` + +If we decide to not include a default value, then `undefined` will be used.