I'm trying to group all the types which have ordered-list-item & unordered-list-item into new object.
How can I simplify the function and reduce multiple return statements?
const data = {
data: [{
areas: [{
sections: [{
rjf: [{
"type": "heading-1",
"text": "A title",
},
{
"type": "ordered-list-item",
"text": "Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Ordered Item B",
},
{
"type": "heading-1",
"text": "A title",
}
]
}]
},
{
sections: [{
rjf: [{
"type": "heading-1",
"text": "Block 2 A title",
},
{
"type": "ordered-list-item",
"text": "Block 2 Ordered Item A",
},
{
"type": "unordered-list-item",
"text": "Block 2 Ordered Item B",
},
{
"type": "heading-1",
"text": "Block 2 A title",
}
]
}]
}
]
}]
};
function parseAreas() {
data[0].areas.forEach(area => {
this.moveToNewObject(area);
})
}
function moveToNewObject(data) {
const areas = data[0].areas;
//console.log(data[0].areas)
const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
return areas.map((area) => {
var sec = area.sections;
return sec.map((section) => {
let lastHeadingIndex = -1;
return section.rjf.reduce((acc, current, index) => {
if (!current.type || !listItemTypes.includes(current.type)) {
lastHeadingIndex = acc.length;
return [...acc, current]
} else {
let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');
if (!listObject) {
listObject = {
type: 'list',
items: [current]
}
return [...acc, listObject];
}
listObject.items = [...listObject.items, current];
return acc;
}
}, [])
});
});
}
console.log('sections', moveToNewObject(data.data));