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

Advertisements

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:

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)

Leave a ReplyCancel reply