我是一名帮助翻译的助手。
我有一个包含多个嵌套数组的复杂数据结构。
以下是当前的结构:
var contentData = {
data: {
content: [
{
type: "column",
sections: [
{
sub: [
{
type: "heading-1",
text: "Heading Text"
}
]
}
]
},
{
type: "acc-item",
sections: [
{
sub: [
{
type: "heading-1",
text: "Heading Text"
},
{
type: "ordered-item",
text: "Item 1"
},
{
type: "unordered-item",
text: "Item 2"
}
]
}
]
},
{
type: "acc-item",
sections: [
{
sub: [
{
type: "heading-1",
text: "Heading Text 2"
}
]
}
]
}
]
}
}
我希望的是:
我想把所有的
ordered-item & unordered-item
分组到一个新对象中,如{type: 'list', items:[all list items]}
。我需要提取所有在
sub
中的项目,并将其推送到新的对象embedded
中,并且它应该放置在根级别下面,如下所示:{type:"acc-item",embedded:[{type:"heading-1",text:"Heading Text 2"}]};
目前我已经完成了以下工作:
我可以把acc-item
分组,但无法分组ordered-item & unordered-item
。
因此,我的最终期望结果应该像这样:
[{
"type": "column",
"embedded": [
{
"type": "heading-1",
"text": "Heading Text"
}
]
},
{
"type": "acc-group",
"items": [
{
"type": "acc-item",
"embedded": [
{
"type": "heading-1",
"text": "Heading Text"
},
{
"type": "list",
"items": [
{
"type": "ordered-item",
"text": "Item 1"
},
{
"type": "unordered-item",
"text": "Item 2"
}
]
}
]
},
{
"type": "acc-item",
"embedded": [
{
"type": "heading-1",
"text": "Heading Text 2"
}
]
}
]
}]
以下是我的代码:
var group,contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"Heading Text"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text"},{type:"ordered-item",text:"Item 1"},{type:"unordered-item",text:"Item 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text 2"}]}]}]}},types=[["list",["ordered-item","unordered-item"]],["accordion",["acc-item"]]];
var result = contentData.data.content.reduce((r, o) => {
var type = (types.find(({ 1: values }) => values.indexOf(o.type) > -1)|| {})[0];
if (!type) {
r.push(o);
group = undefined;
return r;
}
if (!group || group.type !== type) {
group = { type, items: [] };
r.push(group);
}
group.items.push(o);
return r;
}, []);
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';
"ordered-item", "unordered-item"
在列内没有分组。 - user007var contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"标题文本"},{type:"ordered-item",text:"项目 1"},{type:"unordered-item",text:"项目 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"标题文本"},{type:"ordered-item",text:"项目 1"},{type:"unordered-item",text:"项目 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"标题文本 2"}]}]},{type:"column",sections:[{sub:[{type:"heading-1",text:"标题文本"},{type:"ordered-item",text:"项目 1"},{type:"unordered-item",text:"项目 2"}]}]}]}};
吗? - user007[{type:"column",embedded:[{type:"heading-1",text:"标题文本"},{type:"list",items:[{type:"ordered-item",text:"项目1"},{type:"unordered-item",text:"项目2"}]}]}];
。 - user007