使用Java脚本将类Unix路径转换为JSON

我正在从python迁移到javascrip。因此,现在,我正在处理一个Reaction项目,其中需要将一些类似Unix的路径转换为json。实际上,没有文件夹,它们是由&q;/&q;连接的类别列表。 以下是我所拥有的:

  • Category Model将类别和插件游戏保存为由&qot;/";
  • 连接的类别列表
const categorySchema = mongoose.Schema({
    name: { type: String, required: true },
    slug: { type: String, unique: true }, // Repr the route
    image: { type: String },
    topLevel: { type: String },
    description: { type: String },
}, { timestamps: true });

类别的一种表示形式如下:

{
  name: "embedded",
  slug: "/electronics/embedded",
  image: "/some/image.png",
  topLevel: "electronics",
  description: "This is a brief description."
}

现在我想要的是当我有一个这样的对象列表

[
  {
    id: 1,
    name: "embedded",
    slug: "/electronics/embedded",
    image: "/some/image.png",
    topLevel: "electronics",
    description: "This is a brief description."
  },
  {
    id: 2,
    name:"electonics",
    slug:"/electronics",
    topLevel: "electronics",
    image: "/some/image.png",
    description: "..."
  },
  {
    id: 3, 
    name: "house",
    slug: "/house",
    topLevel: "house",
    image: "/some/image.png",
    description: "...",
  }
]

要从插件中获得类似Unix的路径,如下所示:

[
  {
     id: 2,
     node: "electronics",
     children: [{
       id: 1,
       node: "embedded",
       children: [],
     }],
   },
   {
     id: 3,
     node: "house",
     children: []
   },
]

这才是我真正努力想要得到的。如果有人能帮上忙,我们非常欢迎。


解决方案

基于昨天关于我有没有尝试过的评论,我基本上想出了一些东西,但仍然不完美,因为我没有走到整棵树的深处。 根据输入数据和我想要的输出类型,这是我的第一次尝试:

function listToTree(list) {
    var node,
        i,
        roots = [];

    for (i = 0; i < list.length; i += 1) {
        node = list[i];
        var slugList = node.slug.split("/").filter((x) => x !== "");
        var children = [];

        if (slugList.length > 1) {
            var parent = slugList.shift();
            var parentNode = {
                node: parent,
                id: node.id,
                children: [],
            };
            roots.push(parentNode);
            for (var j = 0; j < slugList.length; j++) {
                var child = {
                    id: node.id,
                    node: slugList[j],
                    children: [],
                };
                children.push(child);
            }
            roots[i].children = [...children];
        } else {
            roots.push({
                node: node.topLevel,
                id: node.id,
                children: [],
            });
        }
    }
    return roots;
}

输出:

const roots = listToTree(exampleData);
console.log(roots[0]);

{
  node: 'electronics',
  id: 1,
  children: [ { id: 1, node: 'embedded', children: [] } ]
}

所以,我仍然需要一些帮助,老实说,这里的回答还不完美,灵感来自Halcyon在here

中的回答

相关文章