I have a multi level nested JSON object as shown below. I am trying to find the parental hierarchy up until the root for a given key value. What will be the best way to achieve this.
Sample scenario: If I search for "Grand Child 111", I should get all the parents of "Grand Child 111" i.e. Child 11, Parent 1. The existing solution on stack overflow return sibling of the direct parent as well which isn't needed. I need only the direct parent object and grand parent object just not the their names to be retrieved.
I have tried the other solution in my previous question. It didn't work.
[{ "name": "Parent 1", "children": [{ "name": "Child 11", "children": [{ "name": "Grand child 111", "children": [] }] }, { "name": "Child 12", "children": [{ "name": "Grand child 121", "children": [] }] }, { "name": "Child 2", "children": [{ "name": "Grand child 21", "children": [] } ] } ] }, { "name": "Parent 2", "children": [{ "name": "Child 21", "children": [{ "name": "Grand child 21", "children": [] } ] } ] } ]
Please find the jsfiddle link below
jsfiddle.net/jef9ctxz/1
I am stuck at with the array of parent node names however I would need the entire parent object. Expected result :
[{ "name": "Parent 1", "children": [{ "name": "Child 11", "children": [{ "name": "Grand child 111", "children": [] }] }] }]
@JaromandaX I have edited the question with my solution