How do I create a mapping of all the keys to a specific value in a nested dictionary in JavaScript

Viewed 38

I am trying to create a map to display all the keys that are needed to access a specific value inside a nested dictionary.

var example = {"parent1": {
      "parent2": {},
      "parent3": {},
      "parent4": {
        "sub_1": {},
        "sub_2": {
          "sub_sub2": {
            "sub_sub_sub2": ["some list 1"],
            "sub_sub_sub2_1": ["some list 2"]
          },
          "sub_3": {
            "sub_sub3": ["some list 3"]
          }
        },
        "sub_4": ["some list 4"]
      },
      "parent5": {},
      "parent6": {},
      "parent7": {},
      "parent8": {
        "sub_par8": {}
      },
      "parent9": {}
    }} 

I want the output to show me all the keys required to access the values that are lists. For example, if I want to know which values are lists, the output will return something like:

return_list = [
["parent4", "sub_2","sub_sub2", "sub_sub_sub2", ["some list 1"]],
["parent4", "sub_2","sub_sub2", "sub_sub_sub2_1", ["some list 2"]],
["parent4", "sub_3","sub_sub3", ["some list 3"]],
["parent4", "sub_4",["some list 4"]],
]

My thought is that I can then iterate through this nested list to take the information I need. But if you have a better idea as to how to display the information, then please let me know.

I have tried to create a function that sort of does what I'm looking for, but its broken

var sorted = []
var temp = []

function sort(dictionary){
    for (var [key,value] of Object.entries(dictionary)){
        temp.push(key)
        if (value.constructor == Object){
            sort(value)
        }
        else if (value.constructor == Array){
            
            temp.push(value)
            sorted.push(temp)
        }
        temp = []
    }
}

If you run the code above, you'll notice the list sorted is not formatted correctly. Any help would be much appreciated. I've been trying to solve this for quit some time :)

0 Answers
Related