refactor with ternary and small example

This commit is contained in:
Henry Szeto
2018-07-08 15:24:11 -07:00
parent 2465bccb95
commit 6304ab2d11
5 changed files with 1944 additions and 1945 deletions

View File

@ -2,55 +2,30 @@
Return the value in a nested JSON object by the key.
Given the key name (or target), it will look up the key in the object recursively and return the first value if found.
Given the key name (or target), it will map through each key 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.
```
const dig = (obj, target) => {
if (!obj) return;
if (obj[target]) return obj[target];
else {
return( Object.keys(obj).map(key => {
return obj[target] ?
obj[target] :
Object.keys(obj).map(key => {
if (typeof(obj[key]) === "object") {
return dig(obj[key], target);
}
}).filter(defined => defined)[0] );
}
}).filter(defined=>defined)[0]
};
```
```
const data = {
name: "John Doe",
details: {
phone: "9876543210",
email: "john@example.com",
address: {
street: "123 ABC St.",
state: "CA",
zip: "98765"
},
extra1: {
nickName: "Johnny"
},
extra2: {
nickName: "JD"
},
hobby: "coding",
snacks: ["chips", 'candy', 'coke']
},
l1:{
l2:{
l3:{
l4: "4 levels deep."
}
level1:{
level2:{
level3: "some data"
}
}
};
dig(data, 'nickName'); // "Johnny"
dig(data, 'hobby'); // "coding"
dig(data, 'snacks'); // ["chips","candy","coke"]
dig(data, 'l4'); // "4 levels deep."
dig(data, 'blahblah') // undefined
dig(data, 'level3'); // "some data"
dig(data, 'level4'); // undefined
```