I am currently dealing with the problem of writing a recursive function to order some json data. I have several nested arrays of objects that I need to order as separate slides. The structure is similar to the following:
[ { "title": "a", "children": [ { "title": "aa", "children": [ { "title": "aaa" }, { "title": "aab" } ] }, { "title": "ab", "children": [ { "title": "aba" }, { "title": "abb" } ] } ] }, { "title": "b", "children": [ { "title": "ba", "children": [ { "title": "baa" }, { "title": "bab" } ] }, { "title": "bb", "children": [ { "title": "bba" }, { "title": "bbb" } ] } ] } ]
I wrote a recursive function:
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();
It is output:

However, instead of getting data for my third slide in the format:
aah
aba
a-s-a
I would like to get
a-a- [a, b, c]
I was wondering if this is possible, since I am not very good at recursive processes. I hope I was clean and thank you for that. I basically need to keep the original data structure, but remove the first level of depth for each iteration (a slide in the slider that reflects the increase in depth in my data structure).
javascript arrays recursion
J dubuis
source share