【发布时间】:2015-07-30 22:39:39
【问题描述】:
我目前正在处理编写递归函数来订购一些 json 数据的问题。我有几个嵌套的对象数组,我需要将它们排序到单个幻灯片中。结构类似如下:
[
{
"title": "a",
"children": [
{
"title": "a-a",
"children": [
{
"title": "a-a-a"
},
{
"title": "a-a-b"
}
]
},
{
"title": "a-b",
"children": [
{
"title": "a-b-a"
},
{
"title": "a-b-b"
}
]
}
]
},
{
"title": "b",
"children": [
{
"title": "b-a",
"children": [
{
"title": "b-a-a"
},
{
"title": "b-a-b"
}
]
},
{
"title": "b-b",
"children": [
{
"title": "b-b-a"
},
{
"title": "b-b-b"
}
]
}
]
}
]
我写了一个递归函数:
var catalog = {
init: function() {
var _this = this;
$.getJSON("catalog.json", function(data) {
_this.slides = [];
_this.parseCategories(data.catalog.category,-1,0);
});
},
parseCategories: function(array, depth, prevParent) {
++depth;
if (!this.slides[depth]) this.slides[depth] = [];
if (!this.slides[depth][prevParent]) this.slides[depth][prevParent] = [];
this.slides[depth][prevParent].push(array);
for (var i = 0; i < array.length; i++) {
if (array[i].category) {
this.parseCategories(array[i].category, depth, i);
}
}
}
}
catalog.init();
这个输出:
但是,我没有在格式下检索我的第三张幻灯片的数据:
啊啊啊啊
a-b-a
a-c-a
我想得到
a-a-[a,b,c]
我想知道这是否可能,因为我不太擅长处理递归过程。我希望我很清楚,并感谢您阅读本文。 我基本上需要保留我的原始数据结构,但删除每次迭代的第一个深度级别(在表示我的数据结构中增加深度的滑块中滑动)。
【问题讨论】:
-
我不确定我是否理解您的确切问题。不过我最近解决了一个类似的问题,也许that answer 会帮助你。如果不是,请查看您是否可以澄清问题 - 顶部的预期输出图像很有用,与您的实际结果类似的内容将有助于解释。
-
感谢您的回答,不幸的是,我相信我的问题可能会稍微复杂一些。我已经用一张新图像编辑了我的帖子,该图像面对我的函数返回的输出和我实际需要的输出。这个想法是,我需要通过车把模板构建一个滑块,并在孩子和父母之间导航,同时隐藏所有不必要的数据。因此,我的输出必须以每个深度的数组形式返回数据,并在深度增加时将每个子类别结构化为数组。我可以使用多个循环,但我担心性能成本。
-
你能提供你真正的json结构吗?您当前的 json 与图像中的示例不匹配。如果可能的话,用你所做的事情来做一个 jsfiddle
-
与@FabioLuz 相同的请求
-
请提供给定对象的所需订单
标签: javascript arrays recursion