How can I create a dictionary structure with JavaScript?

Viewed 46

I want to create a function that repeats itself until the dict is empty. I get a big dict(parentChild) full of IDs (see below). The key is parent_ID. The dict from parentChild[parent_id] are the children_ids. I get a start parent_ID, and creat a new dict from parentChild with the start parent_ID. For each child_id I want to do the same. The child_id are now the Parent_iD. I want to go own with this until the parent_id has no child_ids.

I usually work with python, so I have my problems with JavaScript.

Dict:

(The Key in the inner dict is the Child_id and the value doesn't matter)

parentChild{
1:{3:1, 4:1....},
2:{3:1, 4:1....},
3:{5:2, 7:1...},
}

So if my start Parent_Id is "1" it should create a new dict(Tree) and repeat it with the child_ids, for that I can again use the child_ids in parentChils again:

Tree{
1{3:{5,7}, 4{}...
}}

My Code:

getTree(pt, id, dict) {

    Object.keys(pt[id.toString()]).forEach(id_Child => {
        dict[id_Child] = getTree(pt[id_Child], id, dict)
        
    })
    return dict
}

id is the Start parent_Id. pt id parentChild dict.The dict is empty dict(Tree).

0 Answers
Related