0

I have an array of objects:

enter image description here

The object looks like this:

applicationNumber: "35028"
denomination: "ZippIT"
denominationNature: "Denomination"
denominationStatus: "SURRENDERED"
publicationCountry: "RU"
publicationType: "PBR"
speciesName: "Triticum aestivum L."

I want to be able to filter that array of objects based on a string. If that string is on any of the values of the object, we return the object.

Any idea on where to start from?

Sonhja
  • 8,230
  • 20
  • 73
  • 131
  • 1
    https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes – Donal Aug 05 '21 at 13:42
  • 3
    What about `const filteredArray = originalArray.filter(item => !Object.values(item).includes('yourstring'))`? – secan Aug 05 '21 at 13:43
  • Yes, if any of them. And normally the keys are dynamic. So Giovanni's solution won't work for me... – Sonhja Aug 05 '21 at 13:44
  • @Sonhja I canceled but you didn't say that keys could be dynamic – Giovanni Esposito Aug 05 '21 at 13:45
  • 1
    @secan I think the OP want the string as a positive indicator to keep the object, so I think you don't need the `!` (which would exclude objects with that string); otherwise, looks like a solid solution – apsillers Aug 05 '21 at 13:45
  • @apsillers, yes, you are right; I misread the question. Thanks for noticing it. So the actual solution would be `const filteredArray = originalArray.filter(item => Object.values(item).includes('yourstring'))` – secan Aug 05 '21 at 13:47
  • With "dynamic" keys I mean that I never know the key as info comes from different places, so I cannot filter based on a known key name. I'm trying the filtering now – Sonhja Aug 05 '21 at 13:49
  • It works perfect! Thanks guys :) – Sonhja Aug 05 '21 at 13:56

1 Answers1

2

I suppose you're looking for a combination of Array#filter and Object.values.

Something like this:

let includesString = arrayOfObjs.filter(object => 
  Object.values(object).includes(targetString)
)

Demo:

let arrayOfObjs = [
  {value1: "target", value2: "not a target"},
  {value3: "also not a target", value4: "target"},
  {value5: "nope"},
  {value6: "target"}
]

let objectsWithTargets = arrayOfObjs.filter(object => 
  Object.values(object).includes("target")
)

console.log(objectsWithTargets)
lejlun
  • 4,140
  • 2
  • 15
  • 31