Rename deepGetter to deepGet

This commit is contained in:
halsn
2019-05-09 18:30:52 +08:00
parent 42fea928ba
commit 829c5beec8
4 changed files with 45 additions and 45 deletions

24
snippets/deepGet.md Normal file
View File

@ -0,0 +1,24 @@
### deepGet
Returns the target value in a nested JSON object, based on the keys array.
Contrust the keys you want in the nested JSON object as an `Array`.
Use `Array.prototype.reduce()` to get value from nested JSON object one by one. if the key exists in object, return target value, otherwise, return null.
```js
const deepGet = (obj, keys) => keys.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, obj)
```
```js
let idx = 2; // or variable from other places
const data = {
foo: {
foz: [1, 2, 3],
bar: {
baz: ['a', 'b', 'c']
}
}
};
deepGet(data, ['foo', 'foz', idx]); // get 3
deepGet(data, ['foo', 'bar', 'baz', 8, 'foz']); // null
```