Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...