Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search function that iterates through an array and returns the values matched init also in the child object

I’m trying to search an array of objects with objects that are nested in, so for example i have this array:

[
{
 website: 'Stackoverflow',
 info: {
  "extension": "com",
  "ssl": true
 }
},
{
 website: 'Faceoobok',
 info: {
  "extension": "com",
  "ssl": true
 }
}
]

So I want to search all fields, and then also search the object inside and return an array with the method filter, also the char cases won’t matter, it needs to return the object in the array even for example Stackoverflow is not the same as stackoverflow with the casing methods that come with JS.

Here is what I’ve tried, and It searches the objects and returns them but It doesn’t search the object inside, what I mean is for example it searchs the website, but not the .info:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const searchMachine = (arr, query) => {
        let queryFormatted = query.toLowerCase();
        return arr.filter((obj) =>
            Object.keys(obj).some((key) => {
                if (typeof obj[key] === 'string') {
                    return obj[key]
                        .toLowerCase()
                        .includes(queryFormatted);
                }
                return false;
            })
        );

>Solution :

You could take a closure over the wanted string and use a recursive approach for objects.

const
    searchMachine = (array, query) => {
        const
            check = (query => object => Object
                .values(object)
                .some(value =>
                    typeof value === 'string' && value.toLowerCase().includes(query) ||
                    value && typeof value === 'object' && check(value)
                ))(query.toLowerCase());
       
        return array.filter(check);
    },
    data = [{ website: 'Stackoverflow', info: { extension: 'com', ssl: true } }, { website: 'Faceoobok', info: { extension: 'com', ssl: true } }];


console.log(searchMachine(data, 'stack'));
console.log(searchMachine(data, 'com'));
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading