如何合并对象数组中的重复数据值

时间:2019-06-21 02:56:35

标签: javascript

如何在js中合并数组

例如,我具有这样的数组

[{
    "team": team1,
    "groupname": "group1",
    "emp-data": [{
        "id": 1,
        "name": "name1",
    }],
},
{
    "team": team1,
    "groupname": "group1",
    "emp-data": [{
        "id": 2,
        "name": "name2",
    }],
},
{
    "team": team2,
    "groupname": "group1",
    "emp-data": [{
        "id": 3,
        "name": "name3",
    }],
}],

我想要这样的输出 -我想将emp-data推送到相同的团队和相同的组名中

[{
    "team": team1,
    "groupname": "group1",
    "emp-data": [{
        "id": 1,
        "name": "name1",
    },{
        "id": 2,
        "name": "name2",
    }],
},
{
    "team": team2,
    "groupname": "group1",
    "emp-data": [{
        "id": 3,
        "name": "name3",
    }],
}]

我尝试循环数组并使用if进行检查,但仍然无法运行

2 个答案:

答案 0 :(得分:0)

您可以使用.reduceteamgroupname分别映射到新对象中的键,该对象保存您的累积对象。然后,您可以使用Object.values来获取累积的对象:

const arr = [{team:"team1",groupname:"group1","emp-data":{id:1,name:"name1"}},{team:"team1",groupname:"group1","emp-data":{id:2,name:"name2"}},{team:"team2",groupname:"group1","emp-data":{id:3,name:"name3"}}];

const res = Object.values(arr.reduce((acc, {team, groupname, ...rest}) => {
  const key = `${team}-${groupname}`;
  const empData = rest["emp-data"];
  if (!(key in acc)) {
    acc[key] = {team, groupname, ...rest};
    acc[key]["emp-data"] = [];
  }
  acc[key]["emp-data"].push({ ...empData});
  return acc;
}, {}));

console.log(res);

答案 1 :(得分:0)

这将合并具有相同teamgroupname的对象

const teams = [{
    "team": "team1",
    "groupname": "group1",
    "emp-data": {
      "id": 1,
      "name": "name1",
    },
  },
  {
    "team": "team1",
    "groupname": "group1",
    "emp-data": {
      "id": 2,
      "name": "name2",
    },
  },
  {
    "team": "team2",
    "groupname": "group1",
    "emp-data": {
      "id": 3,
      "name": "name3",
    },
  }
]

const merged_teams = {};
teams.forEach(team => {
  const merged_team = merged_teams[team.team + team.groupname];
  if (!merged_team) {
    merged_teams[team.team + team.groupname] = team;
    team["emp-data"] = [team["emp-data"]]
    return;
  }
  merged_team["emp-data"].push(team["emp-data"])
});

console.log(Object.values(merged_teams))