字符串数组到树数据结构

字符串数组到树数据结构

本文介绍了字符串数组到树数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is data returned from server containing an array of strings as hierarchy like this:

[
 "house.bedroom.bed",
 "house.kitchen.spoon",
 "house.kitchen.knife",
 "house.bedroom.sofa",
 "house.bedroom.tv",
 "plants.trees",
 "house.birds.parrot.grey"
 ...]

我如何从中创建树型数据结构,以树状形式输出数据。

how do i create a tree data structure out of it to make Output the data in tree form.

like

root
  house
    bedroom
      bed
      sofa
      tv
    kitchen
      spoon
      knife
    birds
      parrot
        grey
  plants
    trees

最简单的方法是什么?

what is the most simple way to do so ?

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

and is there any way to reverse it ? for example of asked knife i want to return house.kitchen.knife

预先感谢

推荐答案

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

You could take an array with nested arrays where the first element is the name.

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

For finding a wanted string, it uses a recursive approach by keeping the path to the actual elements for later joining a wanted string.

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

... right, why an array and not a funky object? Glad that you asked. Arrays allows to maintain a specific order without relying on actual implementation of ordered objects.

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于字符串数组到树数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:52