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?

8
  • 1
    stackoverflow.com/questions/2722159/… Commented Aug 5, 2021 at 13:42
  • 3
    What about const filteredArray = originalArray.filter(item => !Object.values(item).includes('yourstring'))? Commented Aug 5, 2021 at 13:43
  • Yes, if any of them. And normally the keys are dynamic. So Giovanni's solution won't work for me... Commented Aug 5, 2021 at 13:44
  • @Sonhja I canceled but you didn't say that keys could be dynamic Commented Aug 5, 2021 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 Commented Aug 5, 2021 at 13:45

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.