繁体   English   中英

两个对象数组之间的匹配 javascript

[英]match between two array of objects javascript

我正在构建一个 api 来为商店添加订单,在 function 中我收到身份属性(clientId ...)和一个订单数组,如下所示:

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

然后我从 DB 获取包裹的价格,这样得到最新的价格:

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

我的问题是如何重建order数组以匹配每个 package 及其价格,如下所示:

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

谢谢

嵌套循环

 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)

只需将unitPrice添加到现有order数组中即可:

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

处理这个问题的方法不止一种。 从可维护性和可读性的角度来看,我将分两步进行:

1 - 将 package [{packageid,price}]的数组转换为 map {packageid {packageid:price}

这将使在代码中使用 elsewere 变得更容易这是一种方法: https://stackoverflow.com/a/26265095/8541886

2 - map 以上订单项目

您可以使用Array.map()或简单for循环将价格添加到订单数组

以下是代码的外观:

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

使用 Lodash merge 可以将两个 arrays 合并为一个。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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