refactor with ternary and small example
This commit is contained in:
@ -11,4 +11,4 @@ const functionName = arguments =>
|
||||
|
||||
```js
|
||||
functionName('sampleInput'); // 'sampleOutput'
|
||||
```
|
||||
```
|
||||
|
||||
@ -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
|
||||
```
|
||||
|
||||
1
test/dig/dig.js
Normal file
1
test/dig/dig.js
Normal file
@ -0,0 +1 @@
|
||||
module.exports = dig;
|
||||
6
test/dig/dig.test.js
Normal file
6
test/dig/dig.test.js
Normal file
@ -0,0 +1,6 @@
|
||||
const expect = require('expect');
|
||||
const dig = require('./dig.js');
|
||||
|
||||
test('dig is a Function', () => {
|
||||
expect(dig).toBeInstanceOf(Function);
|
||||
});
|
||||
3833
test/testlog
3833
test/testlog
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user