I'm trying to filter a nested json object by keys based on user inputs, but the amount of keys can be completely dynamic. I also need the search to be based on index / depth.
For example if you take this json:
values = {
1: {
4: {
9: {
...
},
10: {
...
}
},
7: {
12: {
...
},
15: {
...
},
18: {
...
}
}
},
2: {
5: {
7: {
...
}
}
}
}
I want the following results:
search = [1]
result:
{
1: {
4: {
9: {
...
},
10: {
...
}
},
7: {
12: {
...
}
15: {
...
}
18: {
...
}
}
}
}
search = [1, 4]
result:
{
4: {
9: {
...
},
10: {
...
}
}
}
search = [1, 4, 9]
result:
{
9: {
...
}
}
search = [2, 5]
result:
{
5: {
7: {
...
}
}
}
I initially thought I could just go result = values[2][5]
but as the keys and json are completely dynamic in both content and depth it's not going to work.
I've tried using filter but it only works at one level as I need to know the X previous keys first.
Anyone have any ideas?
Edit
This was marked as a duplicate of this post Search key in nested complex JSON but it's not quite the same as I am not searching the entire object for the first result of that key. The keys aren't always unique, e.g. they could be elsewhere in the whole object, so I need to traverse through the object in order.