Giora Guttsait Giora Guttsait - 6 months ago 7
Javascript Question

JS turning dot seperated strings into hierarchical objects

I'm trying to convert a list of strings to an hierarchical tree.

An example of a JSON I would get would 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 is an object, and each sublogger is a child of it's parent.

Each logger is an object, that might contain other objects that are his subloggers. And moreover, like
three.two
in
three.one.three.two
, because there isn't another logger under
three.one.three
, it would be considered as a single logger and not a father logger. Another example is
four.one.some.more.stuff
. Because there are no other loggers under
four
, it would just be a single logger under the same logic as before

{
"one": {
"one": { },
"two": { },
"three": {
"one" : { }
}
},
"two": { },
"three": {
"one": {
"three.two" : { }
}
},
"four.one.some.more.stuff" : { }
}


I'm having difficulty of implementing the above logic (no other sons so it's just one logger and not a father logger).

Some advises or even code examples would be nice

Answer

Finally, the algorithm looks for an existing key in the object and takes it for the next iteration, if not, generate a new object, with the rest of the array as 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);

Comments