javascript - js each loop add one more depth to an object or array -


i have array of pages urls, need make hierarchy of out it.

so this:

   allpages = [        { "url": "/polygon/color/red.html", "name": "red" },         { "url": "/polygon/color/blue.html", "name": "blue" },         { "url": "/polygon/shape/tri.html", "name": "triangle" },         { "url": "/weight/heavy.html", "name": "heavy item" }    ]; 

to this:

sitemap = [     polygon:         color:             [{url:"red.html", name:"red"}],             [{url:"blue.html", name:"blue"}],         shape:             [{url:"tri.html", name:"triangle"}],     weight:          [{url:"heavy.html", name:"heavy item"}], ]; 

the final structure can object or array. can use js, not jquery nor php.

edit: changed input data array of objects. sorry making harder.

fiddle: https://jsfiddle.net/ss92kw4a/2/

several steps:

first split strings arrays:

for(i in all){     all[i] = all[i].substring(1).split("/");      } 

next recursive insertion:

function insert(o, a){     if(a.length == 0){return; }     if(!o[a[0]]){         o[a[0]] = {};     }     insert(o[a[0]], a.slice(1)); } 

we start recursion this:

ans = {};  all.foreach(function(entry){     insert(ans, entry); }); 

all done. result tree in ans object:

console.log(ans); 

enter image description here

update: code makes last level array: https://jsfiddle.net/ss92kw4a/3/


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -