为什么来自snapshot.before和snapshot.after的相同对象不相等? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有一个云函数来递增计数器,只有当快照中的某些字段发生变化时(在这种情况下为“练习”)。

在我的云功能中,我有这个检查总是因为某些原因而触发:

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...
}

日志语句完全相同:

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

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

我该怎么做才能确保快照中的这些值被视为相等?

谢谢。

typescript google-cloud-firestore google-cloud-functions javascript-objects snapshot
1个回答
2
投票

在Javascript中,对象是引用类型。如果你这样做:

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

它将是错误的,因为Javascript正在阅读:

ObjectReference1 === ObjectReference2

有些事情你可以为determine the equality of two Javascript Objects但如果你的对象那么少我会做一个JSON.stringify平等

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
© www.soinside.com 2019 - 2024. All rights reserved.