javascript - JS turning dot seperated strings into hierarchical objects -
i'm trying convert list of strings hierarchical tree.
an example of json be:
{ "log_names": [ "one", "one.one", "one.two", "one.three", "one.three.one", "two", "three", "three.one", "three.one.three.two", "four.one.some.more.stuff" ] }
output
here, each level object, , each sublogger child of it's parent.
each logger object, might contain other objects subloggers. , moreover, three.two
in three.one.three.two
, because there isn't logger under three.one.three
, considered single logger , not father logger. example four.one.some.more.stuff
. because there no other loggers under four
, single logger under same logic before
{ "one": { "one": { }, "two": { }, "three": { "one" : { } } }, "two": { }, "three": { "one": { "three.two" : { } } }, "four.one.some.more.stuff" : { } }
i'm having difficulty of implementing above logic (no other sons it's 1 logger , not father logger).
some advises or code examples nice
finally, algorithm looks existing key in object , takes next iteration, if not, generate new object, rest of array key.
var data = { "log_names": ["one", "one.one", "one.two", "one.three", "one.three.one", "two", "three", "three.one", "three.one.three.two", "four.one.some.more.stuff"] }, object = {}; data.log_names.foreach(function (a) { var temp = object; a.split('.').every(function (b, i, bb) { if (b in temp) { temp = temp[b]; return true; } temp[bb.slice(i).join('.')] = {}; }); }); console.log(object);