1

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));
David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    First of all, [don't put methods on `Object.prototype` like that](https://stackoverflow.com/q/13296340/1048572) or even [at all](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice)! – Bergi Mar 18 '22 at 17:39
  • Related: https://stackoverflow.com/a/35047888/271415 – jarmod Mar 18 '22 at 17:39
  • array filter(). – epascarello Mar 18 '22 at 17:39
  • Since you're diffing/intersecting/combining only lists of strings, not the objects themselves, you probably should not make these methods of `Object`. And for array intersection etc, [yes there are shorter ways to do it](https://stackoverflow.com/q/1885557/1048572) – Bergi Mar 18 '22 at 17:42
  • @Bergi so instead should it use normal functions or make a class that inherits the `Object` type? – David542 Mar 18 '22 at 17:54
  • @David542 I'd recommend normal functions, yes. Also consider `{union:false}.union({intersection: true})` - such methods are no good on a prototype, unless you're working with a restricted set of properties – Bergi Mar 18 '22 at 18:45

1 Answers1

1

A slightly different and shorter way to do it would be as follows:

function diff(obj1, obj2) {
    let keys = Object.keys(obj2);
    return Object.keys(obj1).filter((elem) => !keys.includes(elem))
};
function same(obj1, obj2) {
    let keys = Object.keys(obj2);
    return Object.keys(obj1).filter((elem) => keys.includes(elem));
}
function union(obj1, obj2) {
    let keys = [...Object.keys(obj1), ...Object.keys(obj2)];
    return Array.from(new Set(keys));
}

let obj1 = {x: 1, y: 2};
let obj2 = {x: 3, z: 4}
console.log(diff(obj1, obj2));
console.log(same(obj1, obj2));
console.log(union(obj1, obj2));
David542
  • 104,438
  • 178
  • 489
  • 842