2

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"} ]

3 Answers 3

3
myArray.filter((item) => 
 Object.entries(myFilter).every(([key, val]) => item[key] === val))
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

0
myArray.filter((item) => Object.keys(item).every((key) => !myFilter[key]|| myFilter[key] === item[key]))

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.