refactor map/filter with reduce
This commit is contained in:
@ -2,19 +2,22 @@
|
|||||||
|
|
||||||
Return the value in a nested JSON object by the key.
|
Return the value in a nested JSON object by the key.
|
||||||
|
|
||||||
Given the key name (or target), it will map through each key in the object and look for object type.
|
Given the key name (or target), it will loop through each key/value in the object and look for object type.
|
||||||
If value is an object, dig is called recusively until the first matching key/value is found.
|
If value is an object, dig is called recusively until the first matching key/value is found.
|
||||||
|
|
||||||
```
|
```
|
||||||
const dig = (obj, target) => {
|
const dig = (obj, target) =>
|
||||||
return obj[target] ?
|
target in obj
|
||||||
obj[target] :
|
? obj[target]
|
||||||
Object.keys(obj).map(key => {
|
: Object
|
||||||
if (typeof(obj[key]) === "object") {
|
.values(obj)
|
||||||
return dig(obj[key], target);
|
.reduce((acc, val) => {
|
||||||
}
|
if (acc !== undefined) return acc;
|
||||||
}).filter(defined=>defined)[0]
|
if (typeof val === 'object') {
|
||||||
};
|
const v = dig(val, target);
|
||||||
|
return v === undefined ? undefined : v;
|
||||||
|
}
|
||||||
|
}, undefined);
|
||||||
```
|
```
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user