0

I have an array containing an JS-object such as this:

const dataObjs = [
    {
      city: 'Venice',
      name: 'Mr. Smith',
      age: '42'
    },
    {
      city: 'Venice',
      name: 'Mrs. Carter',
      age: '30'
    },
    {
      city: 'Munich',
      name: 'Mr. Mueller',
      age: '30'
    },
    {
      city: 'London',
      name: 'Mr. Spaghetti',
      age: '75'
    }
]

const filterObj = {
  age: '30'
}

/*const filterObj = {
  age: '30',
  city: 'Venice'
}
*/

const theAnswerIs = dataObjs
  .filter(item => item.includes(filterObj))

If the filter object only contains one property, only the one property shall be returned (e.g. age = xxx). If two properties are passed, both properties should be searched (with an and operator). I suppose "include" doesn't work here, because item is no array... ?

rasenkantenstein
  • 357
  • 1
  • 2
  • 16
  • Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Sadaf Niknam Apr 24 '20 at 15:40
  • Well, I have thought of that as well, but then I have to predefine the conditions, they are not variable anymore. What if I pass one prop, or 5 ... Is there a more generic way? – rasenkantenstein Apr 24 '20 at 15:48
  • @rasenkantenstein too bad your post was closed prematurely, I had an answer that would filter according to object filter exact keys/values -- return matches would be all key/values of object filter or nothing at all. The function accepts any object array and an object literal. – zer00ne Apr 24 '20 at 16:32
  • @rasenkantenstein I voted to reopen but that may never come to fruition. Comment to me here if you post a new question. To avoid double posting, rephrase the question with more details. – zer00ne Apr 24 '20 at 16:38
  • @zer00ne: maybe you could post your answer here: https://stackoverflow.com/questions/44330952/filter-array-of-objects-by-multiple-properties-and-values ? – rasenkantenstein Apr 24 '20 at 17:11
  • @rasenkantenstein it's not exactly what your question involves. That so called *"duplicate"* doesn't look like it is comparing each object key/value pairs to another object key/value pairs (exact match: `&&` or `AND`). Or did I misinterpret your objective?. – zer00ne Apr 24 '20 at 17:31
  • 1
    When I was trying to open a new question containing key and value pair in the headline, this post came up: https://stackoverflow.com/questions/55485823/filter-objects-in-array-by-key-value-pairs eventually, I was able to use the last answer in this post. @zer00ne: thank you for the nudge into the right direction. – rasenkantenstein Apr 24 '20 at 18:49

0 Answers0