Ad

Check If Element Present In A JS Object

- 1 answer

I want to check if an "key" is present in a JS object. Is there a way of doing this? +the data can be an arbitrary subbranch within sometree

Example:

var sometree = {
    foo : {
        data : 1
    },
    foo2 : {
        data : 5
    }
}

function checkForKey(key, obj) {
    //If I do "checkForKey(5, sometree)", I want the function
    //to return "sometree.foo2.data".
}
Ad

Answer

You'll need something recursive if the object can be an arbitrary depth:

    var sometree = {
        foo: {
            data: 1
        },
        foo2: {
            data: 5
        }
    }

    function checkForValue( value, json, name ) {
        var result = checkObject( value, json );
        return result ? name +'.'+ result : null;
    }

    function checkObject( value, json ) {
        var keys = Object.keys(json);
        for ( var i = 0; i < keys.length; i++ ) {
            var key = keys[i];
            if ( typeof json[key] === 'object' && json[key] !== null ) {
                var result = checkObject( value, json[key] );
                if ( result )
                    return key +'.'+ result;
            }
            else if ( json[key] === value ) {
                return key;
            }
        }
        return null;
    }

    document.write( checkForValue( 5, sometree, 'sometree' ) );

Ad
source: stackoverflow.com
Ad