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

Filter array of objects with another array of object without knowing which properties are in the objects

I have an array of objects that I would like to filter but I do not know the properties that I have in the objects (neither the data nor the filter array):

myArray = [
   { id: "100", area: "01", country: "AT"},
   { id: "101", area: "02", country: "DE"}, 
   { id: "102", area: "01", country: "DE"},
   { id: "103", area: "03", country: "CH"},
   { id: "104", area: "01", country: "AT"}
]

and my filter is:

myFilter = { area: "01", country: "AT" }

I would like to have this returned:

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

myArrayFiltered = [
   { id: "100", area: "01", country: "AT"},
   { id: "104", area: "01", country: "AT"}
]

How would I go about doing this? Just to be perfectly clear, I do not know the properties that I will be searching for i.e. I do not know which properties myArray or myFilter will have. If the filter contains a key that is not in myArray I would expect an empty array!

PS: I do also not know how many entries are going to be filters by i.e. depending what my users enter I could just get:

myFilter = [ {area: "01"} ]

>Solution :

var myArray  = 
[
    { id: "100", area: "01", country: "AT"},
    { id: "101", area: "02", country: "DE"}, 
    { id: "102", area: "01", country: "DE"},
    { id: "103", area: "03", country: "CH"},
    { id: "104", area: "01", country: "AT"}
 ]

 var  myFilter = { area: "01", country: "AT" }

    var filteredArray = myArray.filter(function(item) {
        return Object.keys(myFilter).every(function(c) {
            return item[c] === myFilter[c];
        });
    } );
    
    console.log(filteredArray)
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