Home > OS >  Best way to filter an array by multiple properties?
Best way to filter an array by multiple properties?

Time:08-16

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.

CodePudding user response:

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);

CodePudding user response:

      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)

  • Related