Last active
June 15, 2018 17:30
-
-
Save nonlogos/bfae6780a757564983e7a2ede1e1e001 to your computer and use it in GitHub Desktop.
Nested Object Search
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<script id="jsbin-javascript"> | |
let search = (needle, haystack, found=[]) => { | |
Object.keys(haystack).forEach(key => { | |
if (typeof haystack[key] === 'object') { | |
search(needle, haystack[key], found); | |
} | |
if (needle === key) found.push(haystack[key]); | |
}) | |
return found; | |
} | |
let data = { | |
person: 'Mike', | |
address: '123 Street, state, country', | |
relatedCustomers: { | |
childObject: { | |
foo: ['bar'], | |
person: 'Hailey' | |
} | |
} | |
}; | |
console.log(search('person', data)); | |
</script> | |
<script id="jsbin-source-javascript" type="text/javascript">let search = (needle, haystack, found=[]) => { | |
Object.keys(haystack).forEach(key => { | |
if (typeof haystack[key] === 'object') { | |
search(needle, haystack[key], found); | |
} | |
if (needle === key) found.push(haystack[key]); | |
}) | |
return found; | |
} | |
let data = { | |
person: 'Mike', | |
address: '123 Street, state, country', | |
relatedCustomers: { | |
childObject: { | |
foo: ['bar'], | |
person: 'Hailey' | |
} | |
} | |
}; | |
console.log(search('person', data));</script></body> | |
</html> |
This file contains hidden or 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
let search = (needle, haystack, found=[]) => { | |
Object.keys(haystack).forEach(key => { | |
if (typeof haystack[key] === 'object') { | |
search(needle, haystack[key], found); | |
} | |
if (needle === key) found.push(haystack[key]); | |
}) | |
return found; | |
} | |
let data = { | |
person: 'Mike', | |
address: '123 Street, state, country', | |
relatedCustomers: { | |
childObject: { | |
foo: ['bar'], | |
person: 'Hailey' | |
} | |
} | |
}; | |
console.log(search('person', data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment