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: '[email protected]', datofbirth: '6/2/1990' };

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

console.log(form);

Result:

{"name":"sample","email":"[email protected]","datofbirth":"6/2/1990"}

Expected Result:

{"name":"sample","email":"[email protected]"}

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

3 Answers 3

2

Not sure this is what you want, hope it helps

const form = { name: '', email: '' };
const data = {
    name: 'sample',
    email: '[email protected]',
    datofbirth: '6/2/1990',
};
Object.keys(form).forEach(key => {
    if (data.hasOwnProperty(key)) {
        form[key] = data[key];
    }
});
console.log(form);

Sign up to request clarification or add additional context in comments.

1 Comment

A little shorter: Object.keys(form).map(key=> form[key] = data[key]);
1

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

form = { ...form, name: data.name, email: data.email };

Comments

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: '[email protected]', datofbirth: '6/2/1990' },
      result = Object.assign(...Object.keys(form).map(k => ({[k] : data[k]})));
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.