Last active
February 20, 2019 04:28
-
-
Save ppeeou/232e16809198a2d6db3f5aa8764e8120 to your computer and use it in GitHub Desktop.
deep obj find value from key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepFindValue(obj, value) { | |
let results = []; | |
return function recur(obj, value) { | |
for (let key of Object.keys(obj)) { | |
if (typeof obj[key] === 'object') { | |
recur(obj[key], value) | |
} else if (obj[key] === value) { | |
results[results.length] = key | |
} | |
} | |
return results | |
}(obj, value); | |
} | |
const a = { | |
b: { | |
c: 1, | |
d: 'ddd', | |
g: { | |
e: { | |
f: { | |
h: { | |
j: { | |
c: 'good' | |
} | |
} | |
} | |
} | |
} | |
}, | |
f: { | |
g: { | |
h: 'good' | |
} | |
} | |
} | |
const results = deepFindValue(a, 'good');; | |
console.log(results) | |
//[ 'c', 'h' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment