Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter array of objects in which not all keys are present – JS

I have an array of objects:

[
  {
      "id": "1",
      "LB1": "Kod produktu: PMPSB216IN80",
      "Type": "Figurki"
  },
  {
      "id": "2",
      "Type": "Głowa Do Stylizacji"
  },
  {
      "id": "3",
      "LB1": "Kod produktu: 97834",
      "Type": "Pluszak"
  },
]

Than I’m defining a string: ‘97834’

And I want to filter the array based on LB1 value:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

filteredProducts = productList.filter(product => product.LB1.replace('Kod produktu: ', '').toLowerCase() === this.props.searchTerm.toLowerCase());

However as you can see above – not all objects contain this LB1 – and the function is throwing an error:

Test.js:101 Uncaught TypeError: Cannot read properties of undefined (reading 'replace')

>Solution :

You could add a condition, in your filter function, that checks for the existance of that property. Here, i’m using the in operator, to validate just that.

const productList = [
  {
      "id": "1",
      "LB1": "Kod produktu: PMPSB216IN80",
      "Type": "Figurki"
  },
  {
      "id": "2",
      "Type": "Głowa Do Stylizacji"
  },
  {
      "id": "3",
      "LB1": "Kod produktu: 97834",
      "Type": "Pluszak"
  },
]

const searchTerm = '97834' /*  this.props.searchTerm.toLowerCase() */;

const filteredProducts = productList.filter(product => 'LB1' in product && product.LB1.replace('Kod produktu: ', '').toLowerCase() === searchTerm );

console.log('output', filteredProducts);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading