字符串数组到树数据结构

Joh*_*awn 6 javascript treeview data-structures

从服务器返回的数据包含一个字符串数组作为层次结构,如下所示:

[
 "house.bedroom.bed",
 "house.kitchen.spoon",
 "house.kitchen.knife",
 "house.bedroom.sofa",
 "house.bedroom.tv",
 "plants.trees",
 "house.birds.parrot.grey"
 ...]
Run Code Online (Sandbox Code Playgroud)

我如何创建一个树形数据结构,以便以树形形式输出数据。

像这样:

root
  house
    bedroom
      bed
      sofa
      tv
    kitchen
      spoon
      knife
    birds
      parrot
        grey
  plants
    trees
Run Code Online (Sandbox Code Playgroud)

最简单的方法是什么?

有什么办法可以扭转它吗?例如,我想退回house.kitchen.knife所问的

提前致谢

Nin*_*olz 5

您可以采用带有嵌套数组的数组,其中第一个元素是名称。

为了查找所需的字符串,它使用递归方法,保留实际元素的路径,以便稍后加入所需的字符串。

...对了,为什么是数组而不是时髦的对象?很高兴你问了。数组允许维护特定的顺序,而不依赖于有序对象的实际实现。

function find([key, values], string, temp = []) {
    var result;
    temp = temp.concat(key);
    if (key === string) {
        return temp.slice(1).join('.');
    }
    values.some(a => result = find(a, string, temp));
    return result;
}

var array = ["house.bedroom.bed", "house.kitchen.spoon", "house.kitchen.knife", "house.bedroom.sofa", "house.bedroom.tv", "plants.trees", "house.birds.parrot.grey"],
    result = array.reduce((r, s) => {
        ('root.' + s).split('.').reduce((a, item) => {
            var array = a.find(([v]) => v === item);
            if (!array) {
                a.push(array = [item, []]);
            }
            return array[1];
        }, r);
        return r;
    }, []).pop();

console.log(find(result, 'knife')); // house.kitchen.knife
console.log(find(result, '42'));    // undefined, what else?
console.log(result);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)