Created
October 30, 2015 13:57
-
-
Save VivienAdnot/0b595c503d49e7b46994 to your computer and use it in GitHub Desktop.
To ensure that an objects matches the expected structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var target = { | |
prop1: "123", | |
prop2: "456", | |
prop3: { | |
A: "1", | |
B: "2" | |
} | |
}; | |
var schema = [ | |
{ key: "prop1" }, | |
{ key: "prop2" }, | |
{ | |
key: "prop3", | |
children: [ | |
{ key: "A"}, | |
{ key: "B"} | |
] | |
} | |
]; | |
validateObject(target, schema); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var validateObject = function (target, schema) { | |
var result = { | |
status: true, | |
propertyNotFound: null | |
}; | |
var error = function (propertyNotFound) { | |
result.status = false; | |
result.propertyNotFound = propertyNotFound; | |
}; | |
if (!target) { | |
error("target is null"); | |
return result; | |
} | |
if (!schema) { | |
error("schema is null"); | |
return result; | |
} | |
var tokenKey = "key"; | |
var tokenChildren = "children"; | |
for (var index = 0; index < schema.length; index++) { | |
if (target.hasOwnProperty(schema[index][tokenKey]) === false) { | |
error(schema[index][tokenKey]); | |
return result; | |
} | |
if (schema[index].hasOwnProperty(tokenChildren) === true) { | |
for (var indexChildren = 0; indexChildren < schema[index].children.length; indexChildren++) { | |
var resultChildren = validateJson(target[schema[index][tokenKey]], schema[index].children[indexChildren]); | |
if (resultChildren.status === false) { | |
error(resultChildren.propertyNotFound); | |
return result; | |
} | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment