[
{
"parent_id":None,
"sub_cats":[
{
"parent_id":472,
"descr":"D",
"level":1,
"id":508,
"order":0,
"sub_cats":[
{
"parent_id":472,
"sub_cats":[
{
"parent_id":508,
"sub_cats":[
],
"descr":"FOO",
"level":2,
"id":1076,
"order":0
}
],
"descr":"Bar",
"level":1,
"sub_cats_ids":[
]
}
]
},
{
"parent_id":472,
"descr":"E",
"level":1,
"id":490,
"order":1
}
],
"descr":"A",
"level":0,
"id":472,
"order":0
},
{
"parent_id":None,
"sub_cats":[
],
"descr":"B",
"level":0,
"id":544,
"order":1
}
]
A > D > FOO
function getDescriptionChain(subCats, id) {
for (const subCat of subCats) {
if (subCat.id === id) {
return [subCat.descr];
} else {
const chain = getDescriptionChain(subCat.sub_cats, id);
if (chain.length > 0) {
return [subCat.descr, ...chain];
}
}
}
return [];
}
const subCats = [
{
"parent_id": null,
"sub_cats": [
{
"parent_id": 472,
"descr": "D",
"level": 1,
"id": 508,
"order": 0,
"sub_cats": [
{
"parent_id": 472,
"sub_cats": [
{
"parent_id": 508,
"sub_cats": [
],
"descr": "FOO",
"level": 2,
"id": 1076,
"order": 0
}
],
"descr": "Bar",
"level": 1,
"id": 345,
"sub_cats_ids": [
]
}
]
},
{
"parent_id": 472,
"descr": "E",
"level": 1,
"id": 490,
"order": 1
}
],
"descr": "A",
"level": 0,
"id": 472,
"order": 0
},
{
"parent_id": null,
"sub_cats": [
],
"descr": "B",
"level": 0,
"id": 544,
"order": 1
}
];
const chain = getDescriptionChain(subCats, 1076);
console.log(chain.join(' > ')); // "A > D > Bar > FOO"
subCats = [
{
"parent_id":None,
"sub_cats":[
{
"parent_id":472,
"descr":"D",
"level":1,
"id":508,
"order":0,
"sub_cats":[
{
"parent_id":472,
"sub_cats":[
{
"parent_id":508,
"sub_cats":[
],
"descr":"FOO",
"level":2,
"id":1076,
"order":0
}
],
"descr":"Bar",
"level":1,
"sub_cats_ids":[
]
}
]
},
{
"parent_id":472,
"descr":"E",
"level":1,
"id":490,
"order":1
}
],
"descr":"A",
"level":0,
"id":472,
"order":0
},
{
"parent_id":None,
"sub_cats":[
],
"descr":"B",
"level":0,
"id":544,
"order":1
}
]
def isKeyInDict(d, key):
try:
d[key]
return True
except Exception:
return False
def getDescriptionChain(subCats, id):
for subCat in subCats:
if isKeyInDict(subCat["sub_cats"][0], "id"):
if subCat["sub_cats"][0]["id"] == id:
return [subCat["sub_cats"][0]["descr"]]
else:
chain = getDescriptionChain(subCat["sub_cats"], id)
if len(chain) > 0:
return [subCat["descr"]] + chain
else:
chain = getDescriptionChain(subCat["sub_cats"], id)
if len(chain) > 0:
return [subCat["descr"]] + chain
return []
if __name__ == '__main__':
print(" > ".join(getDescriptionChain(subCats, 1076)))
A > D > FOO