I am looking to compare keys in two objects. Is there a built-in method to do this or a shorter version of something like the following?
// treat keys as enumerableOwn
// 1. Difference: {}.keys() - {}.keys()
Object.prototype.diff = function(obj2) {
let thisKeys = Object.keys(this);
let arr = [];
for (let i=0; i < thisKeys.length; i++) {
let key = thisKeys[i];
if (!(obj2.hasOwnProperty(key))) {
arr.push(key);
}
}
return arr;
}
// 2. Intersection: {}.keys() && {}.keys()
Object.prototype.same = function(obj2) {
let thisKeys = Object.keys(this);
let arr = [];
for (let i=0; i < thisKeys.length; i++) {
let key = thisKeys[i];
if (obj2.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr;
}
// 3. Union: {}.keys() || {}.keys()
Object.prototype.union = function(obj2) {
let arr = Object.keys(this);
for (let key of Object.keys(obj2)) {
if (!(obj1.hasOwnProperty(key))) {
arr.push(key);
}
}
return arr;
}
let obj1 = {x: 1, y: 2};
let obj2 = {x: 3, z: 4}
console.log(obj1.diff(obj2));
console.log(obj1.same(obj2));
console.log(obj1.union(obj2));