1

I'm trying to filter an array and remove the entries that contain certain properties. For example, my array looks like this:

const items = [{a: "apple", b: "banana", c: "coconut"}, {a: "apple"}, {b: "banana, c: "coconut"}];

And I want to filter out the items that have the properties b or c.

Right now I have:

items.filter(item => "b" in item || "c" in item);

but I feel like there is a better way to do this, and set it up so a lot more properties could easily be added in the future.

BNK
  • 11
  • 1
  • 3
    Your code is keeping the items with b or c, not filtering them out. – Barmar Aug 15 '22 at 21:12
  • Does this answer your question? [How to filter an array based on property value, or existence of properties](https://stackoverflow.com/questions/70207150/how-to-filter-an-array-based-on-property-value-or-existence-of-properties) – pilchard Aug 16 '22 at 00:07
  • @pilchard That doesn't show how to do multiple properties, which is what this question is about. – Barmar Aug 16 '22 at 00:38
  • @Barmar then combine it with [How to filter an array of object by multiple property values?](https://stackoverflow.com/questions/59576333/how-to-filter-an-array-of-object-by-multiple-property-values) – pilchard Aug 16 '22 at 08:44
  • @pilchard That question asks how to change "either" to "all". But this question asks how to do "either". It's also not filtering by property values, just by property existence. – Barmar Aug 16 '22 at 14:04

2 Answers2

1

Put the property names in an array, and use .some() to test if any of those properties exists.

const items = [{
  a: "apple",
  b: "banana",
  c: "coconut"
}, {
  a: "apple"
}, {
  b: "banana",
  c: "coconut"
}];

let properties_to_filter = ["b", "c"]
let result = items.filter(item => properties_to_filter.some(prop => prop in item));

console.log(result);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    better to use `Object.hasOwn` over `in` unless you explicitly want to test the entire prototype chain – pilchard Aug 16 '22 at 00:05
0

      const items = [{a: "apple", b: "banana", c: "coconut"}, {a: "apple"}, {b: "banana", c: "coconut"}]

      let filtredKey = ["a"]

      let result = []
      items.map(el => {
        if(el.hasOwnProperty("c"))
          result.push(el)
      })

      console.log(result)