Search code examples
javascriptobject

Object Child Key Path


I want to iterate through nested Object and I want to store the all the child keys path as separate array

{
    "A": {
        "C": {
            "G": {}
        }
    },
    "B": {
        "D": {
            "G": {}
        },
        "E": {
            "H": {}
        },
        "F": {
            "I": {
                "H": {}
            },
            "J": {}
        }
    }
}

I need Array in below format.

A,C,G
B,D,G
B,E,H
B,F,J
B,F,I,H


Solution

  • You can use recursion with Object.entries to get the values.

    Here is an example.

    const data = {
        "A": {
            "C": {
                "G": {}
            }
        },
        "B": {
            "D": {
                "G": {}
            },
            "E": {
                "H": {}
            },
            "F": {
                "I": {
                    "H": {}
                },
                "J": {}
            }
        }
    };
    
    const result = []
    
    function getPaths(data,path=''){
      const list = Object.entries(data)
      if(!list.length){
        result.push(path)
        return
      }
      
      list.forEach(([key,value])=>getPaths(value,path ? path+','+key : key))
    }
    
    getPaths(data)
    
    console.log(result)