Monday, 15 May 2017

Finding all child properties with a certain "key object" in a tree-like js object

I am trying to extend the findKey algorithm (in nodejs) below to support finding all the instances of child objects in the tree matching the keyObj signature. The original algoritm:

Object.prototype.findKey = function(keyObj) {
    var p, key, val, tRet;
    for (p in keyObj) {
        if (keyObj.hasOwnProperty(p)) {
            key = p;
            val = keyObj[p];
        }
    }

    for (p in this) {
        if (p == key) {
            if (this[p] == val) {
                return this;
            }
        } else if (this[p] instanceof Object) {
            if (this.hasOwnProperty(p)) {
                tRet = this[p].findKey(keyObj);
                if (tRet) {
                    return tRet;
                }
            }
        }
    }

    return false;
}

My first naive attempt att accomplishing a find all:

Object.prototype.findAllWithKey = function(keyObject) {
    let objectCopy = Object.assign({}, this);
    console.log('findAll on : \n\n');
    console.log(this);
    let keyFound = false;
    let keysFound = [];
    do {
        console.log("while loop iteration...");
        keyFound = objectCopy.findKey(keyObject);
        console.log(keyFound);
        if (keyFound) {
            keysFound.push(keyFound);
            console.log('\n\nkey found:');
            objectCopy = JSON.parse(JSON.stringify(objectCopy).replace(JSON.stringify(keyFound)+',', ''));
        } else {
            console.log('\n\n key not found');
            keyFound = false;
        }

    } while (keyFound !== false);
    console.log('Broke out of while loop')
};

The usage is as follows:

        let targetObject = response.findAllWithKey({
            name: 'GetStatusCode'
        });

where the response object contains a js tree structure with multiple children and instances of sub-objects with {name: 'GetStatusCode'} in them.

Can you point me in the right direction for finding a better way to implement this since, the JSON stringify/parsing feels uneccesary, (plus it fails at the last object since no , is provided there, this I can fix, but there has to be a better way of accomplishing findAll).



via David Karlsson

No comments:

Post a Comment