To filter an array of objects by removing all the items which don't have a property named "prop3", we can use the filter()
method in combination with the hasOwnProperty()
method.
index.tsx521 chars13 lines
In the above example, we define an array of objects called myArray
. We then use the filter()
method to create a new array called filteredArray
, which contains only the objects from myArray
that have a property named "prop3".
The filter()
method takes a callback function as its argument, which is executed for each item in the array. If the callback function returns true
for an item, that item is added to the new array. If the callback function returns false
, that item is excluded from the new array.
In the callback function, we use the hasOwnProperty()
method to check if the current item has a property named "prop3". If it does, the callback function returns true
, which includes that item in the new array. If it doesn't, the callback function returns false
, which excludes that item from the new array.
gistlibby LogSnag