I have the following array of objects; however this could be any unknown key/value and be infinitely nested, for now this is a testing sample:
[
{
"reference_id": "R123",
"customer": "Person 1",
"customer_email": "person1@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
{
"reference_id": "R1234",
"customer": "Person 2",
"customer_email": "person2@email.com",
"location": "USA",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
{
"reference_id": "R12345",
"customer": "Person 3",
"customer_email": "person3@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
}
]
My current implementation is as follows:
const selected = [
{
term: 'Company 1',
column: 'provider',
},
{
term: 'Person 1',
column: 'customer',
},
];
const recursivelyFilterByValue = () => (value) => selected.every((item) => {
if (!value) return false;
if (typeof value === 'string') {
// console.log('value', value === item.term);
return value === item.term;
}
if (Array.isArray(value)) {
return value.some(this.recursivelyFilterByValue());
}
if (typeof value === 'object') {
return Object.values(value).some(this.recursivelyFilterByValue());
}
return false;
});
const results = data.filter(recursivelyFilterByValue());
Basically I am adding to the "selected" array then using that to filter the data array by. I do want to ensure the key matches the "column" also however I haven't added that yet.
For the input above I would expect to output the below:
[
{
"reference_id": "R123",
"customer": "Person 1",
"customer_email": "person1@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
]
However the output array is empty. If I only search for one term (remove all but one term from selected array) the output is correct for that term however any subsequent terms bring back a blank array.
I'm wondering if my use of .some() is the problem however changing this causes too much recursion errors.
Essentially, I want to return the original parent object so long as there is a key:value match for all my conditions in the selected array, at any level of its children.
Any guidance would be much appreciated, thank you.