Я хочу сгруппировать unordered-list-item
и ordered-list-item
.
Ниже приведена исходная структура:
{
data: {
areas: [{
sections: [{
rjf: [
{
type: "unordered-list-item",
text: "Item 1",
},
{
type: "unordered-list-item",
text: "Item 2",
},
{
type: "paragraph",
text: "This is text",
}]
}]
}]
}
}
Теперь я хочу сгруппировать все элементы списка в новый объект.
Итак, ожидаемая структура:
{
data: {
areas: [{
sections: [{
rjf: [
{
type: "list",
items: [{
type: "unordered-list-item",
text: "Item 1",
},
{
type: "unordered-list-item",
text: "Item 2",
}]
},
{
type: "paragraph",
text: "This is text",
}]
}]
}]
}
}
Итак, я хотел переместить весь массив unordered-list-item and ordered-list-item
в items
, и следующий объект type
, такой как paragraph
, не должен подвергаться воздействию.
Я создал решение в TypeScript, но код был слишком длинным:
const areas = data.areas;
const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
return areas.map(area => {
return area.sections.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];
}
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;
}, []);
});
});
Как я могу достичь той же функциональности, используя lodash?
**** UPDATE ****
Я пытался с lodash, но, похоже, не работает.
var content = {
data: {
areas: [{
sections: [{
rjf: [{
type: "unordered-list-item",
text: "Item 1",
},
{
type: "unordered-list-item",
text: "Item 2",
},
{
type: "paragraph",
text: "This is text",
}
]
}]
}]
}
};
var result = content.data.areas.map((area => {
return area.sections.map(section => {
section.rfj = _.groupBy(section.rfj, 'type');
});
}));
document.body.innerHTML = '' + JSON.stringify(result, null, ' ') + '
;
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>