0

Is it possible to update only the existing property values of an object without adding new properties from another object?

Here is my example.

form = {name: '',email: ''};
data = {name: 'sample', email: 'sample@gmail.com', datofbirth: '6/2/1990' };

form = {...form, ...data};

console.log(form);

Result:

{"name":"sample","email":"sample@gmail.com","datofbirth":"6/2/1990"}

Expected Result:

{"name":"sample","email":"sample@gmail.com"}

I dont want the dateofbirth or any new property added on my form object.

Dekso
  • 541
  • 4
  • 23

3 Answers3

2

Not sure this is what you want, hope it helps

const form = { name: '', email: '' };
const data = {
    name: 'sample',
    email: 'sample@gmail.com',
    datofbirth: '6/2/1990',
};
Object.keys(form).forEach(key => {
    if (data.hasOwnProperty(key)) {
        form[key] = data[key];
    }
});
console.log(form);
iamhuynq
  • 5,357
  • 1
  • 13
  • 36
0

Only add the keys you want in the spread rather than the whole object

form = { ...form, name: data.name, email: data.email };
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

Iterate over all the keys in form and generate a new object using Object.assign and spread syntax.

const form = {name: '',email: ''},
      data = {name: 'sample', email: 'sample@gmail.com', datofbirth: '6/2/1990' },
      result = Object.assign(...Object.keys(form).map(k => ({[k] : data[k]})));
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51