Search code examples
javascriptarraysjsonmatching

match between two array of objects javascript


I'm building an api to add orders for a store, in the function I receive identity attributes (clientId...) and an array of the order as so:

order = [{packageId,quantity},...]

I then get the prices of the packages from to DB the get the latest price as so :

packagePrice= [{packageId,unitPrice}, ...(all the packages that are needed)]

my problem is that how could I reconstruct the order array to match each package with its price as so:

order=[{packageId, quantity, UnitPrice}, ...( all other packages)]

Thank you


Solution

  • Just adding the unitPrice to the existing order array would be:

    order.forEach(
      v1 => v1.unitPrice = packagePrice.find(
        v2 => v1.packageId === v2.packageId
      )?.unitPrice
    );