我有两个顶级数组:products
和prices
。我必须将所有这些price
对象移动到product
下,其中price.productId == product.id
。注意,可以存在任意数量的products
和prices
及其关系。
我目前的解决方案:
1.将所有价格复制到每个产品
1.尝试“删除”所有ID不匹配的价格
问题是我不知道如何在步骤#2中匹配product.id
的值。在下面的示例中,我已经硬编码了该值,请参阅FIXME
注解。
我也愿意接受更好的解决方案。
还要注意两个额外的TODO点(可能会在更合适的解决方案中消失)。
这是实际问题的简化版本来说明这一点。
输入:
{
"products": [
{
"id": "PROD_ID_1",
"name": "Product 1"
},
{
"id": "PROD_ID_2",
"name": "Product 2"
}
],
"prices": [
{
"productId": "PROD_ID_1",
"type": "PRICE_TYPE_1",
"amount": "1.0"
},
{
"productId": "PROD_ID_2",
"type": "PRICE_TYPE_2",
"amount": "2.0"
},
{
"productId": "PROD_ID_1",
"type": "PRICE_TYPE_3",
"amount": "3.0"
},
{
"productId": "PROD_ID_3",
"type": "PRICE_TYPE_4",
"amount": "4.0"
}
]
}
预期输出:
{
"products": [
{
"id": "PROD_ID_1",
"name": "Product 1",
"prices": [
{
"productId": "PROD_ID_1",
"type": "PRICE_TYPE_1",
"amount": "1.0"
},
{
"productId": "PROD_ID_1",
"type": "PRICE_TYPE_3",
"amount": "3.0"
}
]
},
{
"id": "PROD_ID_2",
"name": "Product 2",
"prices": [
{
"productId": "PROD_ID_2",
"type": "PRICE_TYPE_2",
"amount": "2.0"
}
]
}
]
}
我的Jolt规格:
[
// copy all prices to every product
{
"operation": "shift",
"spec": {
"products": {
"*": {
"*": "products[&1].&",
"@(2,prices)": "products[&1].prices"
}
}
}
},
// remove prices where product.id != price.productId
{
"operation": "shift",
"spec": {
"products": {
"*": { // iterate products array
"*": "products[&1].&", // copy everything except prices
"prices": {
"*": { // iterate prices array
"productId": { // value matching --- // copy only matching objects
"PROD_ID_1": { // value <-| // FIXME: should be product.id
"@(2)": "products[&5].prices[&3]"
}
}
}
}
}
}
}
}
// TODO remove null objects from prices arrays
// TODO remove price.productId as it's redundant at this point
]
我的Jolt规格的输出:
{
"products" : [ {
"prices" : [ {
"productId" : "PROD_ID_1",
"type" : "PRICE_TYPE_1",
"amount" : "1.0"
}, null, {
"productId" : "PROD_ID_1",
"type" : "PRICE_TYPE_3",
"amount" : "3.0"
} ],
"id" : "PROD_ID_1",
"name" : "Product 1"
}, {
"prices" : [ {
"productId" : "PROD_ID_1",
"type" : "PRICE_TYPE_1",
"amount" : "1.0"
}, null, {
"productId" : "PROD_ID_1",
"type" : "PRICE_TYPE_3",
"amount" : "3.0"
} ],
"id" : "PROD_ID_2",
"name" : "Product 2"
} ]
}
2条答案
按热度按时间dgtucam11#
您可以使用以下规范
网站http://jolt-demo.appspot.com/上的***演示***是
e4eetjau2#
您可以使用此规范: