// test data for trial runs
const testData = [
{
id: 123488,
dealerCode: "ACb3",
name: "Some Name",
gstin: "string",
pan: "string",
cin: "string",
emails: [
{
name: "Some Email name",
address: "anemail.domain.com",
isPrimary: "boolean"
}
],
phoneNumbers: [
{
countryCode: "9398",
number: "number",
isPrimary: "boolean"
}
],
addresses: [
{
addressLine1: "Florida",
addressLine2: "Street place",
addressLine3: "string",
country: "string",
state: "string",
city: "string",
postalCode: "number",
isPrimary: "boolean"
}
],
status: "string",
statusId: "number"
},
{
id: 88888,
dealerCode: "NMC",
name: "Some Other",
gstin: "string",
pan: "string",
cin: "string",
emails: [
{
name: "An Email thing",
address: "athing.somewhere.org",
isPrimary: "boolean"
}
],
phoneNumbers: [
{
countryCode: "93948",
number: "number",
isPrimary: "boolean"
}
],
addresses: [
{
addressLine1: "Denver",
addressLine2: "Street place",
addressLine3: "string",
country: "string",
state: "string",
city: "string",
postalCode: "number",
isPrimary: "boolean"
}
],
status: "string",
statusId: "number"
}
];
// broke these into separate helper functions, but you can combine all of them except the recursive one if you'd like
const returnFilterResults = (userEntry, dataItems) => {
const compareValues = (entry, dataValue) => {
if ( _.isBoolean(dataValue)) {
return entry === dataValue;
} else if (_.isNumber(dataValue)) {
// if the dataValue is a number, we convert both it and the user's entry (which probably already is a string) to a string to compare
// you can make this comparison more strict if desired
return _.includes(_.toLower(_.toString(dataValue)), _.toLower(entry));
} else if (_.isString(dataValue)) {
return _.includes(_.toLower(dataValue), _.toLower(entry));
} else {
return false;
}
};
const matchesEntryInTree = (entry, dataItem) => {
// if this dataItem is an object or array, let's drill back in again
if (_.isObject(dataItem) || _.isArray(dataItem)) {
// as we recursively move through the tree, check to see if *any* of the entries match, using 'some'
return _.some(dataItem, innerDataItem => {
return matchesEntryInTree(entry, innerDataItem);
});
} else {
// if it's a primitive, then let's compare directly
return compareValues(entry, dataItem);
}
};
// I created a results variable so we could console log here in this snippet
// but you can just return from the filter directly
const results = _.filter(dataItems, dataItem => {
return matchesEntryInTree(userEntry, dataItem);
});
console.log(userEntry, results);
return results;
};
returnFilterResults("place", testData);
// both entries return
returnFilterResults("Denver", testData);
// second entry is returned
returnFilterResults(48, testData);
// both entries return - ID in first, countryCode in second
returnFilterResults(12, testData);
// first entry is returned
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>