refactor with ternary and small example

This commit is contained in:
Henry Szeto
2018-07-08 15:24:11 -07:00
parent 8ee6efc01a
commit 162fe2599b
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. 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) => { const dig = (obj, target) => {
if (!obj) return; return obj[target] ?
obj[target] :
if (obj[target]) return obj[target]; Object.keys(obj).map(key => {
else {
return( Object.keys(obj).map(key => {
if (typeof(obj[key]) === "object") { if (typeof(obj[key]) === "object") {
return dig(obj[key], target); return dig(obj[key], target);
} }
}).filter(defined => defined)[0] ); }).filter(defined=>defined)[0]
}
}; };
``` ```
``` ```
const data = { const data = {
name: "John Doe", level1:{
details: { level2:{
phone: "9876543210", level3: "some data"
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."
}
} }
} }
}; };
dig(data, 'nickName'); // "Johnny" dig(data, 'level3'); // "some data"
dig(data, 'hobby'); // "coding" dig(data, 'level4'); // undefined
dig(data, 'snacks'); // ["chips","candy","coke"]
dig(data, 'l4'); // "4 levels deep."
dig(data, 'blahblah') // undefined
``` ```

1
test/dig/dig.js Normal file
View File

@ -0,0 +1 @@
module.exports = dig;

6
test/dig/dig.test.js Normal file
View File

@ -0,0 +1,6 @@
const expect = require('expect');
const dig = require('./dig.js');
test('dig is a Function', () => {
expect(dig).toBeInstanceOf(Function);
});

File diff suppressed because it is too large Load Diff