Update deepGet.md
This commit is contained in:
@ -1,16 +1,17 @@
|
|||||||
### deepGet
|
### deepGet
|
||||||
|
|
||||||
Returns the target value in a nested JSON object, based on the keys array.
|
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`.
|
Compare 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.
|
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
|
```js
|
||||||
const deepGet = (obj, keys) => keys.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, obj)
|
const deepGet = (obj, keys) => keys.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, obj)
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
let idx = 2; // or variable from other places
|
let index = 2;
|
||||||
const data = {
|
const data = {
|
||||||
foo: {
|
foo: {
|
||||||
foz: [1, 2, 3],
|
foz: [1, 2, 3],
|
||||||
@ -19,6 +20,6 @@ const data = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
deepGet(data, ['foo', 'foz', idx]); // get 3
|
deepGet(data, ['foo', 'foz', index]); // get 3
|
||||||
deepGet(data, ['foo', 'bar', 'baz', 8, 'foz']); // null
|
deepGet(data, ['foo', 'bar', 'baz', 8, 'foz']); // null
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user