I am working with a deeply nested json object that looks like the following:
[
{
"categoryId": "1",
"subcategories": [
{
"categoryId": "2",
"subcategories": [
{
"categoryId": "3",
"subcategories": [
{
"categoryId": "4"
},
{
"categoryId": "5"
}
]
},
{
"categoryId": "6"
}
]
}
]
},
{
// another category object
}
]
Keep in mind, not all categories have subcategories - some are two levels deep while others may be three levels deep.
My goal is to traverse the entire structure and retrieve all the categoryId
s within it (order does not matter).
The desired output should look something like this: 1,2,3,4,5,6
I attempted to write a one-liner for this task:
json.map(a => a.subCategories.map(b => b.subCategories ? b.subCategories.map(c => c.subCategories ? c.subCategories.map(d => d.categoryId) : c.categoryId) : b.categoryId)).join()
However, this code snippet does not include the categoryId
s from the top-level categories. I also tried implementing reduce
but without success. Can you assist me in fixing this issue? Thank you.