Skip to content

Instantly share code, notes, and snippets.

@VivienAdnot
Created October 30, 2015 13:57
Show Gist options
  • Save VivienAdnot/0b595c503d49e7b46994 to your computer and use it in GitHub Desktop.
Save VivienAdnot/0b595c503d49e7b46994 to your computer and use it in GitHub Desktop.
To ensure that an objects matches the expected structure
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);
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