Skip to content

Instantly share code, notes, and snippets.

@nonlogos
Last active June 15, 2018 17:30
Show Gist options
  • Save nonlogos/bfae6780a757564983e7a2ede1e1e001 to your computer and use it in GitHub Desktop.
Save nonlogos/bfae6780a757564983e7a2ede1e1e001 to your computer and use it in GitHub Desktop.
Nested Object Search
<!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>
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