迭代创建 json 层

Iteratively create layers of json

我有几个字符串数组,我想从中生成 object。一个例子是这样的。鉴于我有:

let graph = {}
let a = ["Vehicle", "Car", "Sport"]
let b = ["Vehicle", "Car", "Van"]
let c = ["Vehicle", "Truck", "4x4"]

我想创建一个函数,我可以将 a 传递给它,它会将图形更新为:

{
    name: "Vehicle",
    children: [
        {
            name: "Car",
            children: [
                "Sport"
            ]
        }
    ]
}

然后我将 b 传递给函数,图形看到“Vehicle”>“Car”已经存在,因此它只是将“Van”推入 children。然后当 c 被传递时,它将 child 推到 Vehicle children 上。我遇到了循环问题,我无法解释输入可以是任意长度(不仅仅是 3)的事实。我怎样才能像这样遍历 object 的深度?

正如我在评论框中所说,您的预期结果不是有效的节点树,因为第 3 个嵌套节点不应包含数组。

无论如何这是我的答案:

const nodes = new Map([["graph", { children: [], name: 'graph' }]]); // 'graph' is the root node 
const entries = [["Vehicle", "Car", "Sport"], ["Vehicle", "Car", "Van"], ["Vehicle", "Truck", "4x4"]];

function* createNodeIds(entrie, parentId, deep = 0) {
    const name = entrie.shift();
    const nodeId = parentId + '.' + name;
    yield [parentId, nodeId, name, ++deep];
    while (entrie.length)
        yield* createNodeIds(entrie, nodeId, deep);
}

for (const entrie of entries)
    for (const [parentId, nodeId, name, deep] of createNodeIds(entrie, 'graph'))
        if (!nodes.has(nodeId)) {
            const node = { name, children: [] }
            nodes.set(nodeId, node);
            nodes.get(parentId).children.push(deep > 2 ? name : node)
        }

console.log(nodes.get('graph.Vehicle'));