Last active
February 8, 2018 18:18
-
-
Save jhampton/e2ef78b238de923ee436792c8317ea7a to your computer and use it in GitHub Desktop.
Deep JavaScript Object search with filtered keys and array support
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
/** | |
example: | |
const searchDown = getDeepValues( | |
['testId', 'caption', 'model', 'modelId'], | |
action.payload.memoizedProps, | |
['memoizedProps', 'props' ,'child', 'children'] | |
); | |
const searchUp = getDeepValues( | |
['testId', 'caption', 'model'], | |
action.payload.return, | |
['memoizedProps', 'props'] | |
); | |
*/ | |
const getDeepValues = function(keysToMatch:Array<String>, objectToSearch: {}, propsToSearch:Array<string>): {} { | |
let keys = [...keysToMatch]; | |
let result = {}; | |
if (objectToSearch === null || (typeof objectToSearch !== 'object' && !isArray(objectToSearch))) { | |
return {}; | |
} | |
keys.forEach( (o,i) => { | |
if (objectToSearch[o] !== undefined && !!objectToSearch[o]) { | |
result[o] = objectToSearch[o]; // Add to our result | |
keys.splice(i, 1); // Remove the item | |
} | |
}); | |
// We're not done looking if we still have items to fill | |
if (keys.length) { | |
propsToSearch.forEach( (o,i) => { | |
if (typeof objectToSearch[o] === 'object' && objectToSearch[o] !== null) { | |
if (isArray(objectToSearch[o])) { | |
objectToSearch[o].forEach( j => { | |
let deepArraySearchResult = getDeepValues(keys, j, propsToSearch); | |
result = { ...deepArraySearchResult, ...result }; | |
}); | |
} else { | |
let deepSearchResult = getDeepValues(keys, objectToSearch[o], propsToSearch); | |
if (deepSearchResult) { | |
result = { ...deepSearchResult, ...result }; | |
} | |
} | |
} | |
}); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment