gpt4 book ai didi

javascript - 使用 lodash 根据类型对多个对象进行分组

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:01 25 4
gpt4 key购买 nike

我想将 unordered-list-itemordered-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 和 ordered-list-item 移动到 items 数组和以下对象 typeparagraph 应该不会受到影响。

我用 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 实现相同的功能?

****更新****

我尝试使用 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 = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>

最佳答案

return data.areas.map((area => {
return area.sections.map(section => {
return section.rfj = _.groupBy(section.rfj, 'type')
})
})

如果您需要更具体的结构,您可能需要对结果进行一些小的调整,但这应该可以完成大部分工作

关于javascript - 使用 lodash 根据类型对多个对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56238026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com