如何基于id和组相同的键值对合并两个对象

时间:2017-09-13 09:54:04

标签: javascript

      var routePlan = [
      {
        "id" : 1,
        "farmerName" : "Farmer1",
        "farmerId" : 1
      },
      {
        "id" : 2,
        "farmerName" : "Farmer2",
        "farmerId" : 2
      },
      {
        "id" : 1,
        "farmerName" : "Farmer3",
        "farmerId" : 3
      }
    ];

我想合并具有相同id的对象,并使用javascript或angularjs

创建一个新的组合对象
      var routePlan = [
      {
        "id" : 1,
        "farmers" : [
          {
            "farmerName" : "Farmer1",
            "farmerId" : 1
          },
          {
            "farmerName" : "Farmer3",
            "farmerId" : 3
          }
        ]
      },
      {
        "id" : 2,
        "farmerName" : "Farmer3",
        "farmerId" : 2
      }
    ];

请帮助我,我在网上看到了很多例子,但似乎没有什么符合我的要求

2 个答案:

答案 0 :(得分:0)

肯定可以改进,但这是一个有效的解决方案:

let temp = routePlan.reduce(function(acc, item){
    acc[item.id] = acc[item.id] || [];
    acc[item.id].push({ "farmerName": item.farmerName, "farmerId" : item.farmerId });
    return acc;
}, {});

let newRoute = Object.keys(temp).map(function(key){ 
    let newObj = {}

    if (temp[key].length > 1){
        newObj.id = parseInt(key);
        newObj.farmers = temp[key];
    }
    else
    {
        newObj = Object.assign({}, routePlan.find(elem => elem.id == key));
    }

    return newObj;
});

请注意reduce函数用于按id对对象进行分组。

答案 1 :(得分:0)

您可以将哈希表作为对组的引用。

var data = [{ id: 1, farmerName: "Farmer1", farmerId: 1 }, { id: 2, farmerName: "Farmer2", farmerId: 2 }, { id: 1, farmerName: "Farmer3", farmerId: 3 }],
    hash = Object.create(null),
    grouped = data.reduce(function (r, a) {
        function getP(o) {
            return ['farmerName', 'farmerId'].reduce(function (r, k) {
                r[k] = o[k];
                return r;
            }, {});
        }
        if (!(a.id in hash)) {
            hash[a.id] = r.push(a) - 1;
            return r;
        }
        if (!r[hash[a.id]].farmers) {
            r[hash[a.id]] = { id: a.id, farmers: [getP(r[hash[a.id]])] };
        }
        r[hash[a.id]].farmers.push(getP(a));
        return r
    }, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }