I’m attempting to get the keys from an object comparison. If the comparison finds a different object, it should return the key that has to be updated, This is the object:
{
"crm": "",
"dateReceita": "2023-07-27T03:00:00.000Z",
"imagens": [
{
"extension": "jpeg",
"url": "https://firebasestorage.jhsCYMi9l0Zgcw1%2F29544f6b-caec-4e42-93ae-3b4f3f9a854a.jpeg?alt=media&token=78e"
}
],
"laboratorio": "",
"lotes": [
{
"lote": "LOte0",
"loteQtd": "8"
},
{
"lote": "Lote 2",
"loteQtd": "2"
}
],
"nome": "Lotes",
"produto": "Dem",
"quantidade": 10,
"tipo": "Branca",
"vendida": true
}
This is the function I’m runnig:
const getNew = (newObj, oldObj) => {
if (Object.keys(oldObj).length == 0 && Object.keys(newObj).length > 0)
return newObj
const diff = {}
for (const key in oldObj) {
if (newObj[key] && oldObj[key] != newObj[key]) {
diff[key] = newObj[key]
}
}
if (Object.keys(diff).length > 0) return diff
return oldObj
}
Although if I compare that object with itself, it always shows that imagens
and lotes
have some different data, even though it does not
3
Answers
Its very important in high level languages to understand which types are reference type and which types are value type.
For value types, value is compared for equality, for reference types, the reference (memory address) is compared for equality. The reference is the address in memory. So if two reference types are compared for equality, if they are different instances, they will have a different memory address and they will be different.
In your case you are obtaining
imagens
andlotes
because an array is a reference type. If those are different array instances, they are not equal according to==
or===
.For that you need a function that compares the values for you as the one below. Libraries do this for you also as mentioned in the comments.
If you have other reference types in your object that are not arrays and are reference types, you would need to use a value compare function (of your own or from a library) to check for value equality.
Lotes and imagens are also objects so the == or != operators won’t give you the desired result. You’ll need to modify your function to check if the keys hold values that are objects and call it recursively, making your function capable of comparing objects deeply.
Here’s an idea to help you out.