Sonhja
Sonhja

Reputation: 8458

How to filter an array of objects based on value

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?

Upvotes: 0

Views: 85

Answers (1)

lejlun
lejlun

Reputation: 4419

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)

Upvotes: 2

Related Questions