Comparison between two objects

Asked

Viewed 30 times

4

Assuming I have the following objects:

const dataBody = { name:'luiz', email:'[email protected]', cpf:'12345678910' }
const dataDb = { name:'luiz', email:'[email protected]', cpf:'12345678910' }

How do I compare each property of the two objects, and create a new one, with the value(s) of the first one, only when the property(s) is((s) different(s)?

This would be the new object:

const dataRes = { email: '[email protected]'}

for dataBody.email != dataDb.email

  • Would the new object have only one property? The other data will be lost even?

  • The new object would have all the properties that were different between the two compared objects.

  • Cool, so the @Lleon answer already fits you! = D

1 answer

5


See if that helps you:

Object.entries(dataBody).forEach(e => {
  if (dataDb[e[0]] !== e[1]) { dataRes[e[0]] = e[1]; }
})

const dataBody = { name:'luiz', email:'[email protected]', cpf:'12345678910' }
const dataDb = { name:'luiz', email:'[email protected]', cpf:'12345678910' }
const dataRes = {}

Object.entries(dataBody).forEach(e => {
  if (dataDb[e[0]] !== e[1]) { dataRes[e[0]] = e[1]; }
})

console.log(dataRes);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.