gsdev99,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
</head>
<body>
<pre></pre>
<script>
const widgets = [
{
type: "Title",
data: {
title: "title1",
subTitle: "subTitle1"
}
},
{
type: "Title",
data: {
title: "title2",
subTitle: "subTitle2"
}
},
{
type: "Title",
data: {
title: "title3",
subTitle: "subTitle3"
}
},
{
type: "TitleTwo",
data: {
title: "TitleTwo title",
subTitle: "TitleTwo subTitle"
}
},
{
type: "TitleTwo",
data: {
title: "TitleTwo title",
subTitle: "TitleTwo subTitle"
}
},
{
type: "New",
data: {
title: "new title1",
subTitle: "new subTitle1"
}
},
{
type: "New",
data: {
title: "new title2",
subTitle: "new subTitle2"
}
},
{
type: "NewTitle",
data: {
title: "NewTitle title1",
subTitle: "NewTitle subTitle1"
}
},
{
type: "NewTitleTwo",
data: {
title: "NewTitleTwo title",
subTitle: "NewTitleTwo subTitle"
}
}
];
const create = (arr, arrType) => {
const map = new Map, newArr = [];
arr.forEach(o => {
let {type, data} = o;
if(arrType.includes(type)) {
type = `Section${type}`;
if(map.has(type)) map.get(type).push(data);
else {
const children = [data];
map.set(type, children);
newArr.push({type, children})
}
}
else newArr.push(o)
})
return newArr
};
const widgetsTransform = create(widgets, ["Title", "New"]);
document.querySelector("pre").append(JSON.stringify(widgetsTransform, "", 4));
console.log(widgetsTransform)
</script>
</body>
</html>