Skip to content

Instantly share code, notes, and snippets.

@Avery2
Last active April 29, 2024 21:36
Show Gist options
  • Save Avery2/45a459e5c55561f2dfecd28a808c6206 to your computer and use it in GitHub Desktop.
Save Avery2/45a459e5c55561f2dfecd28a808c6206 to your computer and use it in GitHub Desktop.
filter json for key or value that have term
function filterJSON(json, searchTerm, maxDepth = 10) {
// Function to check if the key or value matches the search term
function isMatch(value) {
if (value === null || value === undefined) return false;
if (typeof value === 'symbol') return value.toString().includes(searchTerm.toLowerCase());
if (typeof value === 'object') return false; // Avoid stringifying complex objects here
return value.toString().toLowerCase().includes(searchTerm.toLowerCase());
}
// Recursive function to filter the JSON based on searchTerm and depth
function traverse(json, depth) {
if (depth > maxDepth) return undefined; // Stop recursion if max depth is exceeded
if (typeof json !== 'object' || json === null) {
return isMatch(json) ? json : undefined;
}
const isArray = Array.isArray(json);
const result = isArray ? [] : {};
// Collect keys from objects and symbols
const ownProperties = Object.keys(json);
const symbolProperties = Object.getOwnPropertySymbols(json);
allProperties = [...ownProperties, ...symbolProperties];
let hasValidEntries = false;
for (const key of allProperties) {
const value = json[key];
const filteredValue = traverse(value, depth + 1);
// If the filteredValue isn't undefined, it contains search terms
if (filteredValue !== undefined) {
hasValidEntries = true;
result[key] = filteredValue;
} else if (isMatch(key)) { // Check if key matches the search term
hasValidEntries = true;
result[key] = value;
}
};
// Return the filtered result if it has any valid entries, else undefined
return hasValidEntries ? result : undefined;
}
try {
return traverse(json, 0);
} catch (e) {
console.log('Caught error and returning partial results: ');
return traverse(json, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment