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)
Solution 1:
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; }
Post a Comment for "Javascript Merge Nested Array With Same Object Names?"