Javascript 使用Ramda将对象数组与父属性映射在一起

Javascript 使用Ramda将对象数组与父属性映射在一起,javascript,functional-programming,ramda.js,Javascript,Functional Programming,Ramda.js,我不熟悉函数式编程和ramda。我有一个案例,可以用命令式的方式很容易地解决,但我很难用声明式的方式解决。 我有以下结构,它描述了多个库存 库存=[ { id:'柏林', 产品:[{sku:'123',金额:99}], }, { id:'巴黎', 产品:[ {sku:'456',金额:3}, {sku:'789',金额:777}, ], }, ] 我要做的是将其转换为产品的平面列表,其中包含附加信息,如inventoryId、inventoryIndex和productIndex 产品=[ {

我不熟悉函数式编程和ramda。我有一个案例,可以用命令式的方式很容易地解决,但我很难用声明式的方式解决。 我有以下结构,它描述了多个库存

库存=[
{
id:'柏林',
产品:[{sku:'123',金额:99}],
},
{
id:'巴黎',
产品:[
{sku:'456',金额:3},
{sku:'789',金额:777},
],
},
]
我要做的是将其转换为产品的平面列表,其中包含附加信息,如
inventoryId
inventoryIndex
productIndex

产品=[
{inventoryId:'Berlin',inventoryIndex:1,sku:'123',amount:99,productIndex:1},
{inventoryId:'Paris',inventoryIndex:2,sku:'456',金额:3,productIndex:1},
{inventoryId:'Paris',inventoryIndex:2,sku:'789',金额:777,productIndex:2},
]
正如我之前所写的,以命令式的方式这样做并不是一个问题

函数enrichProductsWithInventoryId(库存){
常量产品=[]
for(const[inventory index,inventory]of inventory.entries()){
for(inventory.products.entries()的常量[productIndex,product]){
product.inventoryId=inventory.id
product.inventoryIndex=inventoryIndex+1
product.productIndex=productIndex+1
产品。推送(产品)
}
}
退货
}
问题是当我试图用拉姆达解决这个问题时。在映射产品时,我不知道如何访问inventoryId。如果能看到一段使用ramda编写的代码就太棒了,它的功能与上面的一样

干杯,
Tomasz

您可以使用
flatMap
轻松做到这一点

const清单=[
{
id:“柏林”,
产品:[{sku:“123”,金额:99}]
},
{
id:“巴黎”,
产品:[
{sku:“456”,金额:3},
{sku:“789”,金额:777}
]
}
];
const products=inventory.flatMap((inventory,inventory index)=>
inventory.products.map((产品、产品索引)=>({
inventoryId:inventory.id,
库存指数:库存指数+1,
sku:product.sku,
金额:product.amount,
productIndex:productIndex+1
})));

控制台日志(产品)我可能会以与Aadit建议类似的方式执行此操作,尽管我会以稍微不同的方式构建它,并使用参数解构

const convert=(库存)=>
flatMap({id:inventoryId,products},i,u,inventoryIndex=i+1)=>
产品地图(
({sku,amount},i,0,productIndex=i+1)=>
({inventoryId,inventoryIndex,sku,amount,productIndex})
)
)
const存货=[{id:“柏林”,产品:[{sku:“123”,金额:99}},{id:“巴黎”,产品:[{sku:“456”,金额:3},{sku:“789”,金额:777}]
console.log(转换(库存))

.as console wrapper{max height:100%!important;top:0}
虽然这样做有效,但您的内部调用在逻辑上不应该是
map
s而不是
flatMap
/
链接索引的
?@ScottSauyet很好。不知道为什么没有抛出一个类型错误。因为它是JS,不应该工作的东西有点。。。直到他们没有!谢谢你们,这很有魅力。我只有一个补充问题。当使用“外部”
inventory
inventoryIndex
变量构建对象时,是否可以将内部
mapIndexed
函数视为纯函数?@TomaszLempart是的,它是纯函数。