如何洗牌数组对象嵌套数组?



我有一个巨大的对象数组。这些对象是这样的:

data = [
{
content: {
...,
depth: 1
},
subContent: []
},
{
content: {
...,
depth: 2
},
subContent: []
},
{
content: {
...,
depth: 3
},
subContent: []
},{
content: {
...,
depth: 2
},
subContent: []
},
{
content: {
...,
depth: 1
},
subContent: []
},
]

我需要这样:

result = [
{
content: {
...,
depth: 1
},
subContent: [
{
content: {
...,
depth: 2
},
subContent: [
{
content: {
...,
depth: 3
},
subContent: []
}
]
},
{
content: {
...,
depth: 2
},
subContent: []
},
], 
{
content: {
...,
depth: 1
},
subContent: []
},
},
]

我需要在前一个较小的subContent中具有较大深度数的结果数组。我使用了一个for循环,从数组的末尾开始,然后到I——,如果下一个subContent的深度+1等于深度,我将较高的深度推入下一个subContent,并从数组中删除索引。

for (let i = arr.length-1; i > 0; i--) {
if (arr[i].content.depth === arr[i-1].content.depth + 1) {
arr[i-1].subContent.push(arr[i]);
arr.splice(i, 1);
} else {
let index = this.findNextLowerIndex(arr[i].content.depth, arr);

// console.log(index);
if (arr[index]) {
arr[index].subContent.push(arr[i]);
arr.splice(i, 1);
}
}
}


findNextLowerIndex(depth: number, arr: any[]): number {
let findIndex = depth - 1;
for (let i = arr.length-1; i > 0; i--) {
if (arr[i].content.depth === findIndex) {
return i;
}
}
}

除了数组的层数为4,3,4,3,2,1时存在多个子内容之外,这种方法是有效的。我得到的是4->3嵌套,4->3->2->1嵌套但不是4->3嵌套在4->3->2->1嵌套的2里面。当有几个带有subContents的图层时,缺少了一些东西。

任何想法?

你看起来像这样吗?

let data = [{ content: { depth: 1 }, subContent: [] }, { content: { depth: 2 }, subContent: [] }, { content: { depth: 3 }, subContent: [] }, { content: { depth: 2 }, subContent: [] }, { content: { depth: 1 }, subContent: [] },]
let result = [];
for (let item of data) {
let node = data.find(v => v.content.depth == item.content.depth - 1)?.subContent || result
node.push(item)
}
console.log(result)

我想这将是您正在寻找的解决方案。

const data = [
{ content: { depth: 1 }, subContent: [] },
{ content: { depth: 2 }, subContent: [] },
{ content: { depth: 3 }, subContent: [] }, 
{ content: { depth: 2 }, subContent: [] },
{ content: { depth: 1 }, subContent: [] },
];
const res = data.reduce((acc, curr) => {
if (curr.content.depth === 1) {
acc.push(curr);
} else {
let node = acc[acc.length - 1]; // Selecting last node
while (node.content.depth !== curr.content.depth - 1) {
if (node.subContent) {
node = node.subContent[node.subContent.length - 1];
} 
}
node.subContent.push(curr);
}
return acc;
}, []);
console.log(res);

最新更新