我目前正在处理一个问题,写一个recrusive函数来订购一些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,i);
}
}
}
}
catalog.init();
这输出:
但是,而不是在格式下检索我的第三张幻灯片的数据:
A-A-A
A-B-A
A-C-一个
我想得到
一个-α-[A,B,C]
我想知道这是否可能,因为我不擅长处理递归过程.我希望我很清楚,谢谢你阅读本文.
我基本上需要保留原始数据结构,但删除每次迭代的第一个深度级别(滑块中的滑动表示我的数据结构中的深度增加).
解决方法
我最近编写了一个算法来递归处理这样的数据.这是一个
jsfiddle和主要功能
console.log('starting');
// data in tree format.
var output = {};
// data in slide format ["a-a-a","a-a-b","b-b-a","b-b-b"]
var outputStrs = [];
parseData(data,output);
console.log(output);
console.log(outputStrs);
function parseData(data,store) {
// go through each element
for (var i = 0; i < data.length; i++) {
var element = data[i];
// used to keep track of where we are in the tree.
var splitElement = element.title.split('-');
var titleStart = splitElement[0];
// console.log(element);
if (_.has(element,'children') && _.isArray(element.children)) {
// if there is a children,then recursively handle it.
store[titleStart] = {};
parseData(element.children,store[titleStart]);
} else {
// if we are at the end,then add in the data differently.
var titleEnd = splitElement[splitElement.length-1];
store[titleEnd] = titleEnd;
// create the slides
var slide = [];
for (var j = 0; j < splitElement.length; j++) {
if (j !== splitElement.length - 1) {
slide.push(titleStart);
} else {
slide.push(titleEnd);
}
}
slide = slide.join('-');
if (!_.contains(outputStrs,slide)) outputStrs.push(slide);
}
}
}
使用此数据,输出应该类似
a
a
a
b
b
b
a
b
而outputStrs将类似于a-a- [a,b,c]
希望这可以帮助!!!