OTRAY
OTRAY

Reputation: 115

I need to recursively check a dynamic Tree Structure in Javascript

I need your help. So the goal this time is that i want to recursively check my tree structure.

Basically this is what i need it to do: enter image description here

On the on side i have a so called treeNode (example: 'Article.Artnr') and on the other a so called contextEntry (which has an 'Article'). I need to check if the name in treeNode exists in contextEntry, if it exists i need to check the type of it and than go on. Now the tricky Part: The next name in the namesSplit is 'Artnr' which i need to check if it is an property from 'Article' in the contextEntry. Again if it is i need to check it's type and go on. I don't know beforehand how deep my structure will be so i really would appreciate your help on this one.

let namesSplit = treeNode.name.split('.');

let key = namesSplit[0];

let contextEntry = exprData.contextEntry.find(_x => _x.name === key);

I have implemented my Recursive check like so:

function recursive(names, contextEntry) {
        for (let i = 0; i < names.length; i++) {
            if (names[i] === contextEntry.name) {
                // getType(contextEntry.value);
                console.log('Name found in Context: ' + names[i]);
                continue;
            }
            if (names[i] == Object.keys(contextEntry.value)) {
                console.log(getType(contextEntry.value));
                console.log('Child Name found in Context: ' + names[i]);
                // console.log(Object.values(contextEntry.value));
            }
        }
    }
    recursive(namesSplit, contextEntry);

I also have to check the type of every value from the Context. There are 4 possible datatypes: Primitive, Array of Primitive, Object, Array of Objects

if the value in the context is either Primitive or an Array of Primitives it will throw an error, if it is an Object i need to just extract the value of it and if it is an Array of Objects i need to find the right object and than extract the value from it

VariableType is an enum. My Check Function is implemented like so:

function getType(contextEntry.value) {
        if (Array.isArray(contextEntry.value)) {
            for (let i of contextEntry.value) {
                if (isPrimitive(i)) {
                    return VariableType.ARRAY_OF_PRIMITIVES;
                }
            }
            if (contextEntry.value.some(val => typeof val === 'object')) {
                return VariableType.ARRAY_OF_OBJECTS;
            }
        }
        if (typeof contextEntry.value === 'object' && contextEntry.value !== null) {
            return VariableType.OBJECT;
        }
        if (isPrimitive(contextEntry.value)) {
            return VariableType.PRIMITIVE;
        }
    }

Upvotes: 0

Views: 280

Answers (0)

Related Questions