Skip to content

Instantly share code, notes, and snippets.

@qgustavor
Last active August 29, 2015 14:03
Show Gist options
  • Save qgustavor/c83ba65cd7876d4c2552 to your computer and use it in GitHub Desktop.
Save qgustavor/c83ba65cd7876d4c2552 to your computer and use it in GitHub Desktop.
Advanced compilation version of hasChainOfKeys
// Example usage:
var example1 = {foo: {bar: 1}},
example2 = {foo: {bar: 1, qux: 1}},
example3 = {foo: {BAZ: 1}},
template1 = {foo: {bar: 1}}
template2 = {foo: {bar: {qux: 1}}}},
// returns true: all keys from the template exist in the object
hasChainOfKeys(example1, template1);
// returns true: all keys from the template exist in the object
hasChainOfKeys(example2, template1);
// returns false: object doesn't have `foo.bar`
hasChainOfKeys(example3, template1);
// returns false: foo.bar exists, but it isn't an object
hasChainOfKeys(example1, template2);
/**
* Tests if object has the same keys as a template:
* @param {Object} obj The object to be tested.
* @param {Object} tmpl The template to be used.
*/
function hasChainOfKeys (obj, tmpl) {
var prop;
// Checks every property of the template:
for (prop in tmpl) {
if (tmpl.hasOwnProperty(prop)) {
// Checks if the object have this property:
if (obj.hasOwnProperty(prop)) {
// Also recurse the object chain:
if (typeof tmpl[prop] === 'object')
if (typeof obj[prop] === 'object') {
if (!hasChainOfKeys(obj[prop], tmpl[prop])) {
return false;
}
} else {
return false;
}
}
} else {
return false;
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment