JavaScript: given an array of strings:
[\'properties.dimensions.length\', \'properties.name\']
what would be the best way to use these to vali
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