Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Implementing various set methods for objects

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));

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!