我创建以下对象,
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}]}]
谁能帮帮我?
最佳答案
@Nithin 你的代码很好,但它试图将 filtered price 数组 插入 product.prices 数组,这会将结果数组转换为数组而不是数组目的。所以一个简单的修改就会产生魔力。
这是它的优化代码。
let products = [{id:1, name: 'a'}, {id:2, name: 'b'}];
let 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}];
products.map(prod=>{
// filter returns an array which can be directly assigned to prices
prod.prices=prices.filter(pric=>pric.id===prod.id);
});
//Print the result stored in products with its corresponding prices
console.log(products);
关于javascript - 在node.js中合并具有不同格式的多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58056310/