Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
Filter array of objects in which not all keys are present - JavaScript

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:

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')
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Check to see if LB1 exists - if it doesn't, filter it out as if it didn't match your search term (here I'm using logical AND:

filteredProducts = productList.filter(product => product.LB1 != null && product.LB1.replace('Kod produktu: ', '').toLowerCase() === this.props.searchTerm.toLowerCase());
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda