Home > Enterprise >  Filter array of objects by array strings and match with substrings of the object
Filter array of objects by array strings and match with substrings of the object

Time:10-31

Actual Code
//return arrayOfObjects.filter((object) => searchTags.every((tag) => Object.values(object).includes(tag)))

array of objects =

let searchTags= ['damiencbib','ADLs'];
    {
        "key": "ACCOR02a",
        "type": "techreport",
        "AUTHOR": "ACCORD",
        "INSTITUTION": "ACCORD",
        "KEYWORDS": "damiencbib adl",
        "MONTH": "June",
        "TITLE": "'Etat de l'art sur les Langages de Description d'Architecture (ADLs)",
        "URL": "http://projects.infres.enst.fr/accord/",
        "YEAR": "2002",
        "BDSK-URL-1": "http://projects.infres.enst.fr/accord/"
    },
    {
        "key": "ACM94b",
        "type": "article",
        "AUTHOR": "ACM",
        "INSTITUTION": "ACM",
        "JOURNAL": "Communications of the ACM",
        "KEYWORDS": "scglib",
        "MONTH": "May",
        "NUMBER": "5",
        "TITLE": "Reverse Engineering",
        "VOLUME": "37",
        "YEAR": "1994"
    }

Expected result is only the first object in the array because it contains both 'damiencbib','ADLs' inside. Something is not working as expected for me, I was thinking to use Regex. Thank you in advance.

CodePudding user response:

You need to check some value as well.

const
    searchTags = ['damiencbib', 'ADLs'],
    data = [{ key: "ACCOR02a", type: "techreport", AUTHOR: "ACCORD", INSTITUTION: "ACCORD", KEYWORDS: "damiencbib adl", MONTH: "June", TITLE: "'Etat de l'art sur les Langages de Description d'Architecture (ADLs)", URL: "http://projects.infres.enst.fr/accord/", YEAR: "2002", "BDSK-URL-1": "http://projects.infres.enst.fr/accord/" }, { key: "ACM94b", type: "article", AUTHOR: "ACM", INSTITUTION: "ACM", JOURNAL: "Communications of the ACM", KEYWORDS: "scglib", MONTH: "May", NUMBER: "5", TITLE: "Reverse Engineering", VOLUME: "37", YEAR: "1994" }],
    result = data.filter(object => searchTags.every(tag => Object
        .values(object)
        .some(s => s.includes(tag))
    ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related