【发布时间】:2021-05-08 08:10:36
【问题描述】:
我是函数式编程和 ramda 的新手。我有一个案例,可以很容易地以命令式的方式解决,但我在声明式的方式上遇到了困难。 我有以下结构,它描述了多个库存。
inventories = [
{
id: 'Berlin',
products: [{ sku: '123', amount: 99 }],
},
{
id: 'Paris',
products: [
{ sku: '456', amount: 3 },
{ sku: '789', amount: 777 },
],
},
]
我想要做的是将其转换为一个平面产品列表,其中包含inventoryId、inventoryIndex 和productIndex 等附加信息。
products = [
{ inventoryId: 'Berlin', inventoryIndex: 1, sku: '123', amount: 99, productIndex: 1 },
{ inventoryId: 'Paris', inventoryIndex: 2, sku: '456', amount: 3, productIndex: 1 },
{ inventoryId: 'Paris', inventoryIndex: 2, sku: '789', amount: 777, productIndex: 2 },
]
正如我之前所写,以命令式的方式执行此操作不是问题。
function enrichProductsWithInventoryId(inventories) {
const products = []
for (const [inventoryIndex, inventory] of inventories.entries()) {
for (const [productIndex, product] of inventory.products.entries()) {
product.inventoryId = inventory.id
product.inventoryIndex = inventoryIndex + 1
product.productIndex = productIndex + 1
products.push(product)
}
}
return products
}
问题是当我尝试用 ramda 解决这个问题时。我不知道如何在映射产品时访问inventoryId。很高兴看到一段使用 ramda 编写的代码,与上面的代码相同。
干杯, 托马斯
【问题讨论】:
标签: javascript functional-programming ramda.js