0

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

4 Answers 4

1

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

order.forEach(
  v1 => v1.unitPrice = packagePrice.find(
    v2 => v1.packageId === v2.packageId
  )?.unitPrice
);
Sign up to request clarification or add additional context in comments.

Comments

1

There are more than on way to handle this. From a maintainablility and readability stand point i would do it it in two steps :

1 - Convert the array of package [{packageid,price}], to a map {packageid:price} :

This would make it easyer to use elsewere in the code Here is a way to do it: https://stackoverflow.com/a/26265095/8541886

2 - map over the order items

You could use Array.map() or a simple for loop to add the prices to the order array

Here is how the code would look :

// get the unit prices as a map
const unitPrices = packagePrice.reduce( 
   (prices,pakageprice) => {
      prices[pakageprice.packageId] = pakageprice.unitPrice
      return prices
   },
   {} // initial value for unit prices
)

// add it to the order array
const ordersWithPrices = orders.map( order => {
    order.unitPrice = unitPrices[order.packageId]
    return order
} ) 

Comments

1

A nested loop

var packageId = 1277;
var quantity = 2;
var unitPrice = 1.00

var order = [{packageId,quantity}]

var packagePrice= [{packageId,unitPrice}]

order.forEach(function(item) {
  item.unitPrice = packagePrice.find(function(item2) {
    return item2.packageId == item.packageId
  }).unitPrice
})

console.log(order)

3 Comments

Why use map() if you're going to discard the result of the map() operation anyway?
No reason just was a harmless error.
The return of your find() function is incorrect. You're assigning instead of comparing.
0
import { merge } from "lodash";

var object = [{ b: 2, c: 3 }];
var other = [{ b: 2, e: 5 }];

console.log(merge(object, other));

Use Lodash merge that will allow you to merge two arrays into one.

https://codesandbox.io/s/lodash-playground-forked-rjfu80?file=/src/index.js:0-129

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.