简体   繁体   中英

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.

I would love for GraphQL to just ignore the extra field but from what I gathered, that the validation error is built by design.

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.

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 :

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM