Need to implement the search the value includes or not in the array of object, if exists only filter the particular object to display. Here is my solution
let data = [
{
"name": "Human Capital Management (HCM)",
"description": "data entry with automatic data syncing capabilities.",
"listingType": "integration",
"connectors": [
{
"name": "oracle",
"description": "our global platform",
"companyName": "Oracle",
},
{
"name": "greenhouse",
"description": "our global platform",
"companyName": "greenhouse",
}
]
},
{
"name": "Applicant tracking system (ATS)",
"description": "data entry with automatic data syncing capabilities.",
"listingType": "integration",
"connectors": [
{
"name": "HiBob",
"description": "our global platform",
"companyName": "HiBob",
},
{
"name": "greenhouse",
"description": "our global platform",
"companyName": "greenhouse",
}
]
},
]
Search value is
let searchVal = 'Greenhouse'
filtering function
let responseData = []
await Promise.all(data.map(async (value)=> {
if(value.name.includes(searchVal)) {
responseData.push(value)
}
if(value.listingType.includes(searchVal)) {
responseData.push(value)
}
if(Array.isArray(value.connectors)) {
let connectors = await filterConnection(value.connectors, searchVal)
if(Array.isArray(connectors) && connectors.length > 0) {
responseData.push({
...value,
connectors
})
}
}
}))
return responseData
Need to implement the search function with more efficient code, kindly suggest the solution.
3
Answers
You could implement it like this:
You can recursively construct a new data array with matching string properties in objects regardless of data structure.
Given code provided in the question it’s not clear whether for example if
listingType
matches, should beconnectors
filtered as well or not…This is very simple function. I have included one more object in the data, which doesn’t have
Greenhouse
as a value for testing purposes. I have usedmap
function along withforEach
to check if the objects include the value ‘Greenhouse’ or not.For each object in the data, first, all the values in the object, including that of the nested objects, are collected in an array and checked against the
searchVal
. If a match is found, the object is returned.