【发布时间】:2020-01-23 03:53:09
【问题描述】:
我在下面创建对象,
products = [
{id:1, name: a},
{id:2, name: b},
]
prices = [
{id:1, month:1, price:1},
{id:1, month:2, price:1},
{id:2, month:1, price:1},
{id:2, month:2, price:1},
]
所以我希望输出为产品价格,
product_prices = [
{id:1, name: a, prices: [{id:1, month:1, price:1},{id:1, month:2, price:1}]},
{id:2, name: b, prices: [{id:2, month:1, price:1},{id:2, month:2, price:1}]},
]
下面是我尝试的代码
let subscriptionProductWithPrices = []
subscriptionProducts.forEach(x => {
subscriptionProductMonthPrices.forEach(y => {
if (x.sub_product_id === y.sub_product_id) {
subscriptionProductWithPrices = [
{
id: x.sub_product_id,
name: x.sub_product_name,
unit_id: x.facility_units_name,
price: x.total_price,
quantity: x.sub_product_quantity,
recurring: x.sub_product_recurring,
in_agreement: x.sub_product_in_agreement,
start_date: x.sub_product_start_date,
end_date: x.sub_product_end_date,
prices:
subscriptionProductMonthPrices
}
]
return subscriptionProductWithPrices
}
})
})
此代码仅返回包含所有价格的最后一个产品 ID,但我希望输出如下,
product prices [{id:1, name: a, prices[{{id:1, month:1, price:1},{id:1, month:2, price:1}]}, {id:2, name: b, prices[{{id:2, month:1, price:1},{id:2, month:2, price:1}]}]
有人可以帮我吗?
【问题讨论】:
-
将 "subscriptionProductWithPrices = [" 替换为 subscriptionProductWithPrices.push( 因为您想在匹配时添加到数组中,而不是将其设置为仅当前匹配。这就是为什么它只有我所看到的最后一个结果。可能还有其他一些问题,但让我们在您将所有结果都放入 subscriptionProductWithPrices 数组中后解决它们。
-
@Spangle 使用上面我的代码目前我得到这个结果产品价格 [{id:2, name: b, prices[{id:1, month:1, price:1},{id: 1,月:2,价格:1},{id:2,月:1,价格:1},{id:2,月:2,价格:1}]}]。它以所有价格返回最后一个产品
标签: javascript mysql node.js json