0

Here my first object

const initialValues = {
  prenom: "anne",
  nom: "dupont",
  age: 24
}

Here my second object

const newValues = {
  prenom: "anne",
  nom: "duclos",
  age: 25
}

What I want is when these two objects will be compared, newValues will contain only property that are different from initialValues. It'll return :

newValues = {
  nom: "duclos",
  age: 25
}

Here what I've been able to do so far:

const initialValues = {
  prenom: "anne",
  nom: "dupont",
  age: 24
}
const newValues = {
  prenom: "anne",
  nom: "duclos",
  age: 25
}

function keepChangedValues(object1, object2) {
    
  const keys1 = Object.keys(object1);
  const keys2 = Object.keys(object2);


  for (let key of keys1) {
    if (object1[key] === object2[key]) {
       
        //delete this propreties from newValues
    }
  }
}
keppChangedValues(initialValues, newValues)

Thank you for you help !

user13512145
  • 45
  • 1
  • 5

2 Answers2

1

If you nkow object properties you can add this:

var newObject = {};
if(newValues.prenom != initialValues.prenom) newValues.prenom = newValues.prenom;
if(newValues.nom != initialValues.nom) newObject.nom = newValues.nom;
if(newValues.age != initialValues.age) newObject.age = newValues.age;
Henock
  • 98
  • 11
0

I find the solution. I just need to add inside the if statement delete object2[key]

In this way, ONLY the propreties of the 2nd object which have the same value as the first object will be deleted from the 2nd object.

user13512145
  • 45
  • 1
  • 5