javascript - 在node.js中合并具有不同格式的多个对象

标签 javascript mysql node.js json

我创建以下对象,

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/

相关文章:

javascript - 如何在javascript中更改函数的上下文

javascript - 如何使用 JavaScript 计算器将 "Fractions"添加到输入区域?

javascript - D3 桑基图使用圆形节点代替矩形节点

mysql - 在每次部署时创建复合唯一索引

在复制表中的行时更新所需的 MySQL 特殊 INSERT/SELECT 语句

mysql - 无法通过套接字 ‘/var/lib/mysql/mysql.sock’连接到本地MySQL服务器(2)Fedora Linux

javascript - 语法错误: missing ) after argument list in express

javascript变量对应具有相同ID的DOM元素

node.js - NodeJs 错误 - 无法加载 gRPC 二进制模块,因为它没有为当前系统预期目录安装?

node.js - 如何让 twitter bootstrap 模式在 node js express js 中工作?