Almog
Almog

Reputation: 2837

Javascript merge nested array with same object names?

I have the following array object enter image description here

Here is the array

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)}
]

I need to be able to merge the tags array with the same name of object so I would end up with the following

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

This is my correct code, which creates the object format

// 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);
        }

Upvotes: 0

Views: 331

Answers (1)

Hassan Imam
Hassan Imam

Reputation: 22534

You can use array#reduce to create a new object with name of object as key and the object as its value. Then, you can concat the tags array if its name is already present in the new object. After that, you can use Object.values() to get the merged tags object.

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; }

Upvotes: 2

Related Questions