简体   繁体   中英

Javascript merge nested array with same object names?

I have the following array object 在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM