I am facing an issue with filtering a JSON object that contains nested arrays and objects. Here is an example of the structure:
[
{
name: 'data 1',
users: [
{
username: 'user 1',
full_name: 'name 1',
sources: [
{ type: 'type 1', name: 'source name 1' },
{ type: 'type 2', name: 'source name 2' },
],
},
{
username: 'user 2',
full_name: 'name 2',
sources: [
{ type: 'type 3', name: 'source name 3' },
{ type: 'type 4', name: 'source name 4' },
],
},
],
},
...
];
I need a function that can filter this data recursively based on all its values. For example, if I search for "data 1", it should return only the object containing "data 1" like so:
[
{
name: 'data 1',
users: [...],
},
];
Similarly, searching for "source name 3" should return both "data 1" and "data 2" objects in an array.
I have tried implementing a recursive search function but it returns all data instead of just the filtered data. The function looks like this:
function search(data) {
return data.filter((data) => {
// Implementation logic for recursive search
});
}
While it's easy to filter by a specific key, dynamically filtering by all keys poses a challenge. What approach should I take to successfully filter this JSON object?