如何在 Javascript 中使用子对象值动态查找父对象值 JSON?

How to find the parent JSON object vaue using the child object value dynamically in Javascript?

var obj = [
{
    "name": "A1",
    "children": [
        {
            "name": "A1-level1-child1",
            "children": [
                {
                    "name": "A1-level2-child1",
                    "children": [
                        {
                            "name": "A1-level3-child1",
                            "children": []
                        },
                        {
                            "name": "A1-level3-child2",
                            "children": []
                        }
                    ]
                }
            ]
        },
        {
            "name": "A2-level1-child1",
            "children": []
        }
    ]   
},
{
    "name": "B1",
    "children": [
    ]   
}

];

从上面的 JSON 对象,如果我检查值 "A1-level3-child1",函数应该给我它的父名称 "A1-level2-child1"。同样,如果我检查 "A2-level1-child1",那么它应该给我父值 "A1"。

GoGo 这个代码。

var parentMap = {}
function getParentMap(arr, parent) {
    if (!(arr instanceof Array)) {
        return;
    }

    for (o of arr) {
        parentMap[o.name] = parent;
        if (o.children && o.children.length) {
            getParentMap(o.children, o);
            //getParentMap(o.children, o.name);
        }
    }
}

var arr = [{
    "name": "A1",
    "children": [{
            "name": "A1-level1-child1",
            "children": [{
                "name": "A1-level2-child1",
                "children": [{
                        "name": "A1-level3-child1",
                        "children": []
                    },
                    {
                        "name": "A1-level3-child2",
                        "children": []
                    }
                ]
            }]
        },
        {
            "name": "A2-level1-child1",
            "children": []
        }
    ]
},
{
    "name": "B1",
    "children": []
}];

getParentMap(obj, null);
parentMap["A1-level3-child1"].name

如果你能重新定义这个结构,你可以在每个节点上添加'parent',这样更容易操作。

您可以迭代数组或子项,如果找到节点则使用短路。

function getParentName(array, name, parent = 'root') {
    var result;
    array.some(o => result = o.name === name && parent
                          || o.children && getParentName(o.children, name, o.name));
    return result;
}

var array = [{ name: "A1", children: [{ name: "A1-level1-child1", children: [{ name: "A1-level2-child1", children: [{ name: "A1-level3-child1", children: [] }, { name: "A1-level3-child2", children: [] }] }] }, { name: "A2-level1-child1", children: [] }] }, { name: "B1", children: [] }];

console.log(getParentName(array, "A1-level3-child1")); // A1-level2-child1
console.log(getParentName(array, "A2-level1-child1")); // A1