Question is similar to: How can I check that two objects have the same set of property names? but only one difference
I want to check:
var objOne = {"a":"one","b":"two","c":{"f":"three_one"}};
var objTwo = {"a":"four","b":"five","c":{"f":"six_one"}};
have the same set of keys in all level?
For example deepCheckObjKeys(objOne, objTwo)
would return true
where deepCheckObjKeys(objOne, objThree)
return false
, if:
var objThree = {"a":"four","b":"five","c":{"g":"six_one"}};
Since objThree.a.c.f
is undefined
in objThree.
A function like this:
'use strict';
function objectsHaveSameKeys() {
for (var _len = arguments.length, objects = Array(_len), _key = 0; _key < _len; _key++) {
objects[_key] = arguments[_key];
}
var allKeys = objects.reduce(function (keys, object) {
return keys.concat(Object.keys(object));
}, []);
var union = new Set(allKeys);
return objects.every(function (object) {
return union.size === Object.keys(object).length;
});
}
only checks the first level.
PS: objectsHaveSameKeys() ES6 equivalent:
function objectsHaveSameKeys(...objects):boolean {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
const union = new Set(allKeys);
return objects.every(object => union.size === Object.keys(object).length);
}