string 'properties.dimensions.length' to access hash {properties: {dimensions: {length: 23}}}

JavaScript: given an array of strings:

 ['properties.dimensions.length', 'properties.name']

what would be the best way to use these to validate or access them (in fact just want to verify if the key does exist) in a hash?

I was thinking of string split('.') but I haven't been able to really understand how each of the array values could be used to validate or access the value from a hash.

like ['properties', 'dimensions', 'length'] and then forEach that to drill down, but ideally I'd like to turn that into the equiv of code:

myProperties['properties']['dimensions']['length']

But feel free to say if this is a totally hacky approach... and be nice! :-D

Answers:

Answer

You could try something like this:

function hasProperty(obj, props) {
    if (typeof props === "string") 
        return hasProperty(obj, props.split("."));
    for(var i = 0; i < props.length; i++) {
        if (props[i] in obj) 
            obj = obj[props[i]];
        else 
            return false;
    }

    return true;
}

And call it like this:

var propPath = 'properties.dimensions.length';
console.log(hasProperty(myProperties, propPath));

Demonstration

And here's a recursive alternative:

function hasProperty(obj, props) {
    if (typeof props === "string") 
        return hasProperty(obj, props.split('.'));
    return props.length == 0 || props[0] in obj && hasProperty(obj[props.shift()], props);
}

var propPath = 'properties.dimensions.length';
console.log(hasProperty(myProperties, propPath));

Demonstration

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.