【问题标题】:How to merge duplicate object parent items in array?如何合并数组中重复的对象父项?
【发布时间】:2021-06-29 20:48:12
【问题描述】:

我想合并数组中的对象,以便具有相同 id 的对象(这是一个子对象)可以对 total_price 和 total_quantity 值求和。 这是我的数据数组:

var data = [
        {
            "_id": {
                "month": 5,
                "year": 2021
            },
            "total_price": 145111500,
            "total_quantity": 7
        },
        {
            "_id": {
                "month": 6,
                "year": 2021
            },
            "total_price": 98386000,
            "total_quantity": 5
        },
        {
            "_id": {
                "month": 6,
                "year": 2021
            },
            "total_price": 32500000,
            "total_quantity": 3
        }
    ]

我想合并具有重复“_id”的对象。这是输出结果:

var merge = [
        {
            "_id": {
                "month": 5,
                "year": 2021
            },
            "total_price": 145111500,
            "total_quantity": 7
        },
        {
            "_id": {
                "month": 6,
                "year": 2021
            },
            "total_price": 130886000,
            "total_quantity": 8
        }
    ]

提前致谢。

【问题讨论】:

    标签: javascript arrays object array-merge


    【解决方案1】:

    const data = [
      { "_id": { "month": 5, "year": 2021 }, "total_price": 145111500, "total_quantity": 7 },
      { "_id": { "month": 6, "year": 2021 }, "total_price": 98386000, "total_quantity": 5 },
      { "_id": { "month": 6, "year": 2021 }, "total_price": 32500000, "total_quantity": 3 }
    ];
    
    const res = [...
      // iterate over the list
      data.reduce((map, item) => {
        // construct key from _id
        const key = `${item._id.month}-${item._id.year}`;
        // get prev map value of key if exists
        const prev = map.get(key);
        // update map, if prev not found, set value as item, or update it with the added values
        map.set(
          key, 
          !prev 
            ? item 
            : { ...item, total_price: prev.total_price + item.total_price, total_quantity: prev.total_quantity + item.total_quantity }
        );
        return map;
      }, new Map)
      // return map values
      .values()
    ];
    
    console.log(res);

    【讨论】:

      【解决方案2】:
      var ids = [];
      var merge =  [];
      for (let i = 0; i < data.length; i++) {
        obj = data[i];
        let dupId = false;
        for (let j = 0; j < ids.length; j++) {
          if (ids[j]["month"] == obj["_id"]["month"] && ids[j]["year"] == obj["_id"]["year"]) {
            merge[j]["total_price"] += obj["total_price"];
            merge[j]["total_quantity"] += obj["total_quantity"];
            dupId = true;
            break;
          }
        }
        if (!dupId) {
          ids.push(obj["_id"]);
          merge.push(obj);
        }
      }
      

      代码将:

      • 声明合并数组并将其初始化为空数组
      • 循环遍历数据数组中的所有元素
      • 在内部,检查合并数组中的元素是否重复
      • 如果找到,请添加总数量和总价格
      • 如果没有找到,将元素添加到合并数组中

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2019-07-15
        • 1970-01-01
        • 2016-11-12
        • 2019-12-20
        • 1970-01-01
        • 2019-04-28
        相关资源
        最近更新 更多