JSFiddle - React, Tailwind, and code Playground

by Abhishek Garg

JavaScript

let inventory = [
  {
    brand: 'Parle',
    products: [
      {
        brand: 'Parle Agro',
        products: [
          {
            brand: 'Frooti',
            products: []
          },
          {
            brand: 'Bailey',
            products: []
          }
        ]
      }
    ]
  },
  {
    brand: 'Pepsico',
    products: [
      {
        brand: 'VB',
        products: [
          {
            brand: 'Lays',
            products: []
          },
          {
            brand: 'Kurkure',
            products: [
              {
                brand: 'Mad Angles',
                products: []
              }
            ]
          }
        ]
      },
      {
        brand: 'Pepsi',
        products: []
      }
    ]
  },
  {
    brand: 'Cadbury',
    products: []
  }
];

//Print all the brand names with their parent name by traversing through this JSON. For top level brands use parent as "None".
// Hint : Use Stack 
// e.g. None : Parle, Parle : Parle Agro, Parle Agro : Frooti


//--------------------Only for Interviewer-------------------------


//Solution :

function print(inventory, parent) {
    inventory.forEach(item => {
    	console.log(`${parent} : ${item.brand}`);
    	if(item.products && item.products.length > 0){
      	print(item.products, item.brand);
      }
    });
}

print(inventory, "None");