I have the array of objects as input
shown below. This has property vertical
as type string, platformList
is an array and radar_metadata
is nested object
I want to search for a string and get those object which has string value in it. Its like a search functionality that i am trying to implement.
let input = [
{
"vertical": "Partner",
"platformList": [
"Access"
],
"radar_metadata": {
"state": "Verify",
}
},
{
"vertical": "Integration",
"platformList": [
"Identity"
],
"radar_metadata": {
"state": "Closed",
}
}
]
So i implemented this function to loop through the object elements and get those object whose string matches or is included in the object.
const filterByValue = (array, string) => {
return array.filter((o) =>
Object.keys(o).some((k) =>
o[k].toString().toLowerCase().includes(string.toLowerCase())
)
);
};
When i get this result1, i search for Partner
text in the array of object and i get the result as follows.
let result1 = filterByValue(input, 'Partner')
----Output----
result1 = [
{
"vertical": "Partner",
"platformList": [
"Access"
],
"radar_metadata": {
"state": "Verify",
}
}
]
Now the complexity increases when i want to search for Ident
text or Clos
text. Because these searches are to be performed in nested object (radar_metadata) as well as array (platformList)
let result2 = filterByValue(input, 'Ident')
let result3 = filterByValue(input, 'Clos')
----Output----
result2 = [
{
"vertical": "Integration",
"platformList": [
"Identity"
],
"radar_metadata": {
"state": "Closed",
}
}
]
result3 = [
{
"vertical": "Integration",
"platformList": [
"Identity"
],
"radar_metadata": {
"state": "Closed",
}
}
]
Can someone let me know how to modify my filterByValue
function to include these scenarios too.
You can do this by destrcturing your object:
const filterByValue = (array, string) => {
return array.filter((obj)=>{
// destructure your obj to extract the data
const {vertical, platformList, radar_metadata: {state}} = obj;
// make an array from the destructured data
const data = platformList.concat(state,vertical);
// return if string is included
return data.some( (el)=>el.toLowerCase().includes(string.toLowerCase()) );
});
};
Here is a link for more info on destructuring:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment