Skip to content
Advertisement

How to filter array of objects where object has property tagId or keywordId in JS?

I have an array of objects and I am trying to filter it by checking if the object has property tagId or keywordId. I thought about this but not sure if it’s the correct way.

const filteredProducts = products.filter(product => product.tagId !== undefined || product.keywordId !== undefined)

Is there better way to achieve the above-explained result and get a filtered array of objects which include either tagId or keywordid?

Advertisement

Answer

You are basically manually creating comparisons that already exist as hasOwnProperty() in object prototype

const filteredProducts = 
     products.filter(product => product.hasOwnProperty('tagId') || product.product.hasOwnProperty('keywordId'))

//Or using `Array#some()`
const filteredProducts = 
     products.filter(product => ['tagId','keywordId']
                                  .some(prop => product.hasOwnProperty(prop)))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement