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

后端 未结 1 1982
星月不相逢
星月不相逢 2021-01-24 15:05

JavaScript: given an array of strings:

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

what would be the best way to use these to vali

相关标签:
1条回答
  • 2021-01-24 15:45

    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

    0 讨论(0)
提交回复
热议问题