filter an array by removing all the items which don't have a property named "prop3" in javascript

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.tsx
const myArray = [
  {prop1: 'value1', prop2: 'value2', prop3: 'value3'},
  {prop2: 'value2', prop4: 'value4'},
  {prop1: 'value1', prop3: 'value3'},
  {prop2: 'value2'},
  {prop1: 'value1', prop2: 'value2', prop3: 'value3', prop4: 'value4'}
];

const filteredArray = myArray.filter(item => item.hasOwnProperty('prop3'));

console.log(filteredArray);
// Output: [{prop1: 'value1', prop2: 'value2', prop3: 'value3'}, {prop1: 'value1', prop3: 'value3'}, {prop1: 'value1', prop2: 'value2', prop3: 'value3', prop4: 'value4'}]
521 chars
13 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