Home > database >  Find string in array of objects
Find string in array of objects

Time:06-03

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"
  }
}]

CodePudding user response:

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

CodePudding user response:

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/

  • Related