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.
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);
Only add the keys you want in the spread rather than the whole object
form = { ...form, name: data.name, email: data.email };
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.