【发布时间】:2021-10-27 05:39:17
【问题描述】:
我想在 JavaScript 中创建嵌套数组。
我将得到这样的对象作为输入:
[{size: 12, "text": "aa"}, {size: 11, "text": "ab"}, {size: 10, "text": "ac"}, {size: 12, "text": "ad"}...]
我想比较大小并创建类似于下面给出的结构的数组。我想使用引用来创建相同的,但 JavaScript 没有引用。 o/p 数组会是这样的:
[{
"size": 12,
"text": "a",
"childrens": [{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
},
{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
}
]
},
{
"size": 12,
"text": "a",
"childrens": [{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
},
{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
}
]
}
]
我试过了:
let start = [];
inp.forEach(key => {
let found = false;
while(!found) {
if(start.length === 0 || start[start.length - 1].size === key.size || key.size > start[start.length - 1].size ) {
start.push({...key, childrens: []})
found = true;
}
else if(start[start.length - 1].size > key.size) {
start = start[start.length - 1].childrens;
}
}
})
但在这我知道我正在重新分配开始,这似乎是错误的。 那么如何创建上面给出的数组结构呢? 提前致谢。
【问题讨论】:
-
您能否提供更具体且相互关联的输入和输出?我不明白我们需要对孩子中的文本做什么以及为什么孩子也是数组。
-
您将遍历输入数组,如果该元素的大小大于或等于最后一个数组索引元素的大小,那么您将在数组中创建新元素,如果元素的大小为小于当前数组索引的大小,那么您将转到最后一个数组索引的子级。您将重复此操作,直到找到插入该元素的位置。
-
例如。在上面给定的 i/p 数组中:第一个元素的大小为 12,并且数组没有任何元素,因此您将默认插入它。第二个元素的大小为 11,小于 12,然后您将其作为 12 的子元素插入。第三个元素是
-
你可以假设这是索引。比如1、1.1、1.1.1、1.2、2、2.1、2.1.1、2.1.2
标签: javascript node.js arrays