简体   繁体   中英

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

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM