Ad

How To Find The Parent JSON Object Vaue Using The Child Object Value Dynamically In Javascript?

- 1 answer

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": [
    ]   
}

];

From the above JSON object, if i check the value "A1-level3-child1", the function should give me its parent name as "A1-level2-child1". Same way, if i check for "A2-level1-child1",then it should be give me the parent value as "A1".

Ad

Answer

You could iterate the array or children and use a short circuit if the node is found.

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

Ad
source: stackoverflow.com
Ad