0

I have a cloud function to increment a counter, only if certain fields change within the snapshot ('exercises' in this case).

In my cloud function, I have this check that always fires for some reason:

const before = snapshot.before.data();
const after = snapshot.after.data();     
if (before['exercises'] !== after['exercises']) {
   console.log(before['exercises']);
   console.log(after['exercises']);
   // Increment the counter...
}

And the log statements are identical:

[ { exerciseId: '-LZ7UD7VR7ydveVxqzjb',
    title: 'Barbell Bench Press' } ] // List of exercise objects

[ { exerciseId: '-LZ7UD7VR7ydveVxqzjb',
    title: 'Barbell Bench Press' } ] // Same list of exercise objects

What can I do to ensure that these values within the snapshot get treated as equal?

Thank you.

Mike H
  • 125
  • 1
  • 1
  • 10

1 Answers1

2

In Javascript an object is a reference type. If you make this:

{a: 1} === {a: 1}

It will be false because Javascript is reading:

ObjectReference1 === ObjectReference2

There are things you can to for determine the equality of two Javascript Objects but if your object is that little I would just do a JSON.stringify equality

const before = {
  exerciseId: '-LZ7UD7VR7ydveVxqzjb',
    title: 'Barbell Bench Press' }

const after = {
  exerciseId: '-LZ7UD7VR7ydveVxqzjb',
  title: 'Barbell Bench Press'
};

function areEqual(object1, object2) {
  return JSON.stringify(object1) === JSON.stringify(object2);
}


console.log(areEqual(before, after)); /// true
distante
  • 6,438
  • 6
  • 48
  • 90