I like to build a list of names to an array. It needs to find the name from Level1 and then go through the chain to Level3. If it does not match from Level1 then try Level2, if still no match then try to get the Name from Level3
For example Ouput:
getNames("Office") to return ["Office", "Microsoft", "Software"]
getNames("Apple") to return ["Apple", "Software"]
getNames("Tesla") to return ["Tesla", "Car"]
Data
const data = {
"Level1": [ { "Names": [ "Office" ], "Level": "Level2#Microsoft" } ],
"Level2": [ { "Names": [ "Apple", "Microsoft" ], "Level": "Level3#Software" }, { "Names": [ "Tesla" ], "SubLevel": "Level3#Car" }],
"Level3": [ { "Names": [ "Software" ] }, { "Names": [ "Car" ] } ]
}
I am struggling with how to get data to the next level without writing many if conditions?
Incomplete usage:
function getNames(name) {
const namesBuild = [];
const foundName = data.Level1.find(row => {
return row.Names.find(rowName => rowName === name)
});
if (foundName) {
namesBuild.push(name);
const subLevel = foundName.Level.split("#");
const catLevel = subLevel[0];
const catName = subLevel[1];
// How to continue to find next chain from object without many if conditions?
} else {
// attempt to find next level Level2, if not found then try Level3
}
return namesBuild;
}