Javascript合并具有相同对象名称的嵌套数组?

时间:2017-11-09 05:07:24

标签: javascript

我有以下数组对象 enter image description here

这是数组

tagGroups: Array(6)
[
{name: "Function", tags: Array(1)}
{name: "Function", tags: Array(1)}
{name: "Function", tags: Array(1)}
{name: "Test", tags: Array(1)}
{name: "Test", tags: Array(1)}
{name: "new", tags: Array(1)}
]

我需要能够将tags数组与同一个对象名称合并,所以我最终会得到以下内容

{
            "name": "Tag Group 1",
            "tags": [
                "TagA",
                "TagB",
                "TagC"
            ]
        },

这是我正确的代码,它创建了对象格式

// Creates the final format that can be upload or stored
        for (var i = 0, l = tagGroupsArr.length; i < l; i++) {
            tagGroupsTemp = {name: tagGroupsArr[i].tagGroupName, tags: [tagGroupsArr[i].tag]};
            tagGroupsFinal.push(tagGroupsTemp);
        }

1 个答案:

答案 0 :(得分:2)

您可以使用array#reduce创建一个新对象,其名称为object作为键,对象作为其值。然后,如果concat数组tags已存在于新对象中,则可以name。之后,您可以使用Object.values()来获取合并的标签对象。

const tagGroupes = [{name: "Function", tags: ["TagA"]},{name: "Function", tags: ["TagB"]},{name: "Function", tags: ["TagC"]},{name: "Test", tags: ["TestA"]},{name: "Test", tags: ["TestB"]},{name: "new", tags: ["newA"]}]

const result = tagGroupes.reduce((res, obj) => {
  if(res[obj.name]){
    res[obj.name].tags = res[obj.name].tags.concat(obj.tags);
  } else {
    res[obj.name] = obj;
  }
  return res;
},{});

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