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

103
Vistas
Find string in array of objects

I have two different arrays and I am trying to filter the one while looping the other.

const serviceCodes = 
[
  {
    ...otherStuff...
    "codes": [
      "786410010",
      "787885010"
    ]
  }
]

and

const laborCost = 
[
  {
    "laborCode": "786410010",
    "estimatedCost": {
      "value": -1,
      "currency": "USD"
    }
  },
  {
    "laborCode": "787885010",
    "estimatedCost": {
      "value": -1,
      "currency": "USD"
    }
  }
]

I am looping through serviceCodes and trying to return only the object that matches the laborCode

const serviceMatchesRow = serviceCodes[0].codes.forEach((code) => {
  return laborCost?.find(
    (service) => service.laborCode === code,
  )
})

This is returning undefined as forEach only runs through it, but if I use .map instead, then it return the 2 objects within laborCost. If I change for .find instead, than it returns an array with the laborCode itself ["786410010", 787885010].

So how can I get around this?

The desired output would be something like:

[{
  "laborCode": "786410010",
  "estimatedCost": {
    "value": -1,
    "currency": "USD"
  }
}]
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

forEach method doesn’t return anything

so you should insert the matches objects in new array. or use .map method

const serviceMatchesRow = [];
 serviceCodes[0].codes.map((code) => {
    serviceMatchesRow.push(laborCost.find((service) => { 
        return service.laborCode === code 
        }
    ));
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Problem: You're trying to return from within the foreach block; that will not return anything thats why you see undefined.

Solution: Use map to return while iterating on an array.

const serviceMatchesRow = serviceCodes[0].codes.map((code) => {
  return laborCost.find(
    (service) => service.laborCode === code,
  )
})

Working fiddle: https://jsfiddle.net/240z5u3f/3/

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