user11875917
user11875917

Reputation:

Compare 2 object by keys

I have two objects:

let obj1 = {
  username: Jake,
  progress: 100
};

let obj2 = {
  username: Jake,
  progress: 200,
  updatedAt: timestamphere
};

I want function which will return true if certain keys in those 2 object not the same.

For example it would be username and progress but not updatedAt (would be more when 1.

function compareObjectsByKeys(keys);

for example:

if (compareObjectsByKeys(['username', 'progress']) {
  // do something
}

Upvotes: 0

Views: 297

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50974

You can use .every() on your keys array, to check whether each key-value pair from object one is equal to that of object two. I've also used JSON.stringify so that we can compare arrays and other objects.

const obj1 = {
  username: 'Jake',
  progress: 100
};

const obj2 = {
  username: 'Jake',
  progress: 200,
  updatedAt: 'timestamphere'
}

function compareObjectsByKeys(keys) {
  return !keys.every(k => k in obj1 && k in obj2 && JSON.stringify(obj1[k]) === JSON.stringify(obj2[k]));
}

console.log(compareObjectsByKeys(['username', 'progress'])); // true 
console.log(compareObjectsByKeys(['username'])); // false
console.log(compareObjectsByKeys(['foo'])); // true (in this case undefined != undefined)

Upvotes: 0

Morphyish
Morphyish

Reputation: 4072

You need to pass both objects as well

compareObjectsByKeys(obj1, obj2, keys) {
    for (key of keys) {
        if (obj1[key] !== obj2[key]) {
            return true;
        }
    }

    return false;
}

with keys being an array of strings

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

Use every first to make sure all the keys are in both objects, then use some to check the alternate values.

const obj1 = {username:"Jake",progress:100};
const obj2 = {username:"Jake",progress:200,updatedAt:"timestamphere"};

const compareObjectsByKeys = keys => keys.every(key => key in obj1 && key in obj2) && keys.some(key => obj1[key] != obj2[key]);

console.log(compareObjectsByKeys(["username", "progress"]));

Upvotes: 1

Related Questions