'To get index or matching values from Nested Array of values : Javascript/Typescript/Lodash

I would like to find the matching values by iterating over each array of object values and also to find the path of the matching value. Property to be searched for the value is "subMenu" - It can be either an object or an array of strings.

Example Array :

  mainArray = [
    {
      name: 'mainMenu1',
      subMenu: [
        {
          name: 'subMenuLevel1',
          subMenu: [
            {
              name: 'subMenuLevel2',
              subMenu: ['AAA', 'BBB'],
            },
            {
              name: 'subMenuLevels',
              subMenu: ['CCC'],
            },
          ],
        },
      ],
    },
    {
      name: 'mainMenu2',
      subMenu: ['MMM'],
    },
  ];

Value to be searched \ Input: AAA

I want to find where the value "AAA" is presented by traversing through all the subMenu property in the available nested array of objects ? If "AAA" matches with any of the subMenu Array values may I know how can I take the path of the value as well like the expected output below.

Example Output:

level3 = AAA , 
level2 = subMenuLevel2,
level1 = subMenuLevel1,
mainLevel = mainMenu1


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source