Last active
May 22, 2016 04:15
-
-
Save daniellizik/9a58876c5aec56b13daa3b6e59f493df to your computer and use it in GitHub Desktop.
deepsearch find object
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
'use strict'; | |
function deepsearch_find_first_object(needle, haystack, parent) { | |
let iterable; | |
if (Object.prototype.toString.call(haystack) === '[object Array]') { | |
iterable = haystack; | |
} else if (Object.prototype.toString.call(haystack) === '[object Object]') { | |
iterable = Object.keys(haystack); | |
} else { | |
if (typeof needle === 'function') { | |
if (needle(parent) === true) | |
return parent; | |
else | |
return; | |
} else { | |
let parentKeys = Object.keys(parent); | |
let needleKeys = Object.keys(needle); | |
let match = needleKeys | |
.filter(key => parent[key] && parent[key] === needle[key]) | |
.length === needleKeys.length; | |
if (match === true) | |
return parent; | |
else | |
return; | |
} | |
} | |
for (let i = 0; i < iterable.length; i++) { | |
let key = haystack.hasOwnProperty(iterable[i]) ? haystack[iterable[i]] : iterable[i]; | |
let found = deepsearch_find_first_object(needle, key, haystack); | |
if (found) | |
return found; | |
} | |
} |
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
var fixture = { | |
a: { | |
a1: 'df', | |
a2: 'dlkfj', | |
b: { | |
c: { | |
d: { | |
e: { | |
f: 'mouse' | |
} | |
} | |
}, | |
g: [ | |
5, | |
45, | |
true, | |
null, | |
false, | |
5643635, | |
{ | |
a: { | |
b: { | |
c: { | |
d: 'horse', | |
mouse: 'fake!' | |
} | |
} | |
}, | |
f: [ | |
{}, | |
{}, | |
[], | |
undefined, | |
{ | |
a: 'cat', | |
cl: ['a', 'b', 'c'] | |
} | |
] | |
} | |
] | |
} | |
} | |
}; | |
var result = deepsearch_find_first_object(parent => { | |
if (parent.cl) { | |
if (parent.cl.indexOf('b') > -1) | |
return true; | |
} | |
}, fixture); | |
var result2 = deepsearch_find_first_object({mouse: 'fake!'}, fixture) | |
console.log(typeof result === 'object', 'result should return object'); | |
console.log(result.hasOwnProperty('a'), 'result should have a key'); | |
console.log(result.a === 'cat', 'result should have cat val'); | |
console.log(typeof result2 === 'object', 'result should return object'); | |
console.log(result2.hasOwnProperty('d'), 'result should have a key'); | |
console.log(result2.d === 'horse', 'result should have horse val'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment