Skip to content
Advertisement

How to iterate through a JavaScript object and get parent properties?

I’m iterating through a JS object (obj) and would like to retrieve the parent property of a property. E.g. if k is ‘v9’. Something like k.parent would return ‘c’ and k.parent.parent would return ‘b’. Of course, the syntax is different and that’s what I’m looking for

function iterate(o) {
    
    Object.keys(o).forEach(function (k) {

        if (o[k] !== null && typeof o[k] === 'object') {
            iterate(o[k]);
            return;
        }
        if (typeof o[k] === 'boolean') {

            // e.g. k is 'v9'. How to get its parent properties?
            // like k.parent would return 'c' and k.parent.parent would return 'b'

        }
    });
    
}


const obj = {

    a: {
        'v1': true,
        'v2': true,
        'v3': false
    },

    b: {
        'v4': false,
        'v5': true,
        'v6': false,
        
        
        c: {
            'v7': false,
            'v8': true,
            'v9': false
        }
    }

}

iterate(obj);

Advertisement

Answer

an idea can be to store the parent key as a parameter of iterate function

function iterate(o, parentKey) {
    
    Object.keys(o).forEach(function (k) {

        if (o[k] !== null && typeof o[k] === 'object') {
            iterate(o[k], k);
            return;
        }
        if (typeof o[k] === 'boolean') {
            console.log(k);
            console.log(parentKey);

        }
    });
    
}


const obj = {

    a: {
        'v1': true,
        'v2': true,
        'v3': false
    },

    b: {
        'v4': false,
        'v5': true,
        'v6': false,
        
        
        c: {
            'v7': false,
            'v8': true,
            'v9': false
        }
    }

}

iterate(obj);

Another idea can be to stored a structure fill at each iterate step if there is a parent to the current object use recursive behavior to fill it

function iterate(o, parent) {
    
    Object.keys(o).forEach(function (k) {

        if (o[k] !== null && typeof o[k] === 'object') {
            const nextParent = { name: k };
            if (parent.name) {
               nextParent.parent = parent;
            }
            iterate(o[k], nextParent);
            return;
        }
        if (typeof o[k] === 'boolean') {
            console.log(k);
            console.log(parent);

        }
    });
    
}


const obj = {

    a: {
        'v1': true,
        'v2': true,
        'v3': false
    },

    b: {
        'v4': false,
        'v5': true,
        'v6': false,
        
        
        c: {
            'v7': false,
            'v8': true,
            'v9': false
        }
    }

}

iterate(obj, {});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement