0

I have a JavaScript array with any number of nodes with subCategories as the below format.

{
    "maDetails": [{
            "categoryId": 1,
            "category": "Third Party Applications",
            "subCategories": [{
                "categoryId": 5,
                "category": "Third Party Applications6",
                "subCategories": [{
                    "categoryId": 3,
                    "category": "BMC Remedy"
                }]
            }]
        },
        {
            "categoryId": 1,
            "category": "Third Party Applications",
            "subCategories": [{
                "categoryId": 3,
                "category": "Third Party Applications2",
                "subCategories": [{
                    "categoryId": 3,
                    "category": "BMC Remedy"
                }]
            }]
        }
    ]
}

The subCategories may be any number. I want to map all the subcategories to a single array with its parent category name and ID. what is the easiest way to do that?

vijesh
  • 1,115
  • 1
  • 11
  • 27
  • What have you tried so far? Have you looked into https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map? – evolutionxbox Jun 09 '21 at 11:20
  • https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json – Teemu Jun 09 '21 at 11:23
  • @evolutionxbox I tried the map, But the node may be any in number and may be nested as well. I have confusion how to handle that – vijesh Jun 09 '21 at 11:25
  • 1
    _" I tried the map"_ - please show us, not tell us. – evolutionxbox Jun 09 '21 at 11:28

1 Answers1

1

use a recursive generator function.

let data = { "maDetails": [{ "categoryId": 1, "category": "Third Party Applications", "subCategories": [{ "categoryId": 5, "category": "Third Party Applications6", "subCategories": [{ "categoryId": 3, "category": "BMC Remedy" }] }] }, { "categoryId": 1, "category": "Third Party Applications", "subCategories": [{ "categoryId": 3, "category": "Third Party Applications2", "subCategories": [{ "categoryId": 3, "category": "BMC Remedy" }] }] }] }

function* gen(input) {
    for (let item of input) {
        if (!item.subCategories) continue;
        for (let { categoryId, category } of item.subCategories) {
            yield { parentId: item.categoryId, parentCategory: item.category, categoryId, category, }
        }
        yield* gen(item.subCategories)
    }
}

console.log([...gen(data.maDetails)]);
Nur
  • 2,361
  • 2
  • 16
  • 34