[英]Update object array without adding new properties from another object
Is it possible to update only the existing property values of an object without adding new properties from another object?是否可以只更新 object 的现有属性值而不添加另一个 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.我不想在我的表格 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只在传播中添加您想要的键,而不是整个 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
.遍历
form
中的所有键,并使用Object.assign
和spread syntax
生成新的 object。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.