我想根据其type
对多个对象进行分组。
我正在尝试将unordered-list-item
和ordered-list-item
分组到以下结构中的新对象
listObject = { 类型:“列表”, 项目:[当前] };
当前逻辑将所有有序和无序listItem分组。
现在,我想将类型为accordion-item
的对象归为以下结构,
{
type: 'accordion',
items: [...]
};
如何更新代码以支持将accordion-items
分组到期望的结构?
请帮助。
const content = {
data: {
areas: [{
sections: [{
rjf: [{
type: "paragraph",
text: "(API) as early as possible:",
depth: 1,
},
{
type: "unordered-list-item",
depth: 1,
text: "To your travel agent",
inlineEntityRanges: []
},
{
type: "unordered-list-item",
depth: 1,
text: "During online check-in, from 24 hours up to 1 hour before departure.",
},
{
type: "paragraph",
text: "\nThe API data includes:",
depth: 0,
},
{
type: "unordered-list-item",
text: "Family name and first name",
depth: 1,
},
{
type: "accordion-item",
sections: [{
type: "accordion-title",
value: "accordion-title1",
rjf: []
},
{
type: "accordion-body",
value: "accordion-body1",
rjf: []
}
]
},
{
type: "accordion-item",
sections: [{
type: "accordion-title",
value: "accordion-title2",
rjf: []
},
{
type: "accordion-body",
value: "accordion-body2",
rjf: []
}
]
}
]
}]
}]
}
};
function contentDataMapping(data) {
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;
}, []);
});
});
}
console.log(this.contentDataMapping(content.data));
***** UPDATE *****
当前结构
{
"type": "accordion-item",
"sections": [
{
"type": "accordion-title",
"value": "accordion-title1",
"rjf": []
},
{
"type": "accordion-body",
"value": "accordion-body1",
"rjf": []
}
]
},
{
"type": "accordion-item",
"sections": [
{
"type": "accordion-title",
"value": "accordion-title2",
"rjf": []
},
{
"type": "accordion-body",
"value": "accordion-body2",
"rjf": []
}
]
}
预期:
{
"type": "accordion",
"items": [
{
"type": "accordion-item",
"sections": [
{
"type": "accordion-title",
"value": "accordion-title1",
"rjf": []
},
{
"type": "accordion-body",
"value": "accordion-body1",
"rjf": []
}
]
},
{
"type": "accordion-item",
"sections": [
{
"type": "accordion-title",
"value": "accordion-title2",
"rjf": []
},
{
"type": "accordion-body",
"value": "accordion-body2",
"rjf": []
}
]
}
]
}