Home > database >  How to remove "__typename" field in a loop before mutation
How to remove "__typename" field in a loop before mutation

Time:10-17

I'm getting all the data to the values variable so I'm trying to access values variable and remove the __typenamesfield before the update mutation.

This is what I've tried,

values.profiles.forEach(i => delete i["__typename"]);

But I'm getting this error

TypeError: Cannot delete property '__typename' of #<Object>

In the try block I've created a obj object. This is exactly same object that I'm receiving for values

But If I try to remove __typename from obj it works just fine.

obj.profiles.forEach(i => delete i["__typename"]);

Here is my code,

                <Formik
                    initialValues={initialValues}
                    onSubmit={async (values, { setSubmitting }) => {

                        try {
                            setSubmitting(true);

                            const obj = {
                                "profiles": [
                                    {
                                        "__typename": "Account",
                                        "firstName": "John1",
                                        "lastName": "Doe1",
                                    },
                                    {
                                        "__typename": "Account",
                                        "firstName": "John2",
                                        "lastName": "Doe2",
                                    }
                                ],
                            }

                            obj.profiles.forEach(i => delete i["__typename"]);
                            console.log(obj);

                            values.profiles.forEach(i => delete i["__typename"]);
                            console.log(values);

                            ...
                        } catch (e) {
                            console.log(e)
                        }
                    />

Anything I'm missing?

CodePudding user response:

You can use a utility like omit-deep-lodash

import { omitDeep } from ‘omit-deep-lodash’;
 
const profilesWithOmittedTypename = obj.profiles.map(o => omitDeep(o, ‘__typename));
  • Related