[英]Move a property from one object to another in Javascript
The root of my problem is GraphQL does not allow fields that are not defined by my input type but the data object comes from a single form.我的问题的根源是 GraphQL 不允许我的输入类型未定义的字段,但数据 object 来自单个表单。
I would love for GraphQL to just ignore the extra field but from what I gathered, that the validation error is built by design.我希望 GraphQL 忽略额外的字段,但从我收集到的信息来看,验证错误是有意设计的。
So now, I need to move the property that GraphQL doesn't know and store it in another variable so I can use it in another mutation.所以现在,我需要移动 GraphQL 不知道的属性并将其存储在另一个变量中,以便我可以在另一个突变中使用它。
What I am doing:我在做什么:
const items = formData.items
delete formData.items
I am just wondering if there is any new/better syntax or technique for doing the same thing.我只是想知道是否有任何新的/更好的语法或技术来做同样的事情。
You can destructure from the original object and use spread to get two new variables, items
and newFormData
from your original formData
:您可以从原始 object 解构并使用spread从原始
formData
获取两个新变量items
和newFormData
:
const { items, ...newFormData } = formData
Doing a delete is a code smell.删除是一种代码味道。 It is better if you do:
如果你这样做会更好:
const formData = {myProp:8, items:[1,2,3], anotherProp:12} const {items:items, ...newFormData} = formData console.log(items) console.log(newFormData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.