I want to print all the brand names with their parent name by traversing through this array. For top level brands , parent as "None".
e.g. None : Parle, Parle : Parle Agro, Parle Agro : Frooti
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: []
}
];
I have tried following approach but I'm missing out somewhere.
function brandName(obj){
for (var key in obj) {
var item = obj[key];
if (typeof item === "object"){
brandName(item.products); }
} } brandName(inventory);