0

My data object looks like this:

    const data = {
        name: 'John',
        lastName: 'Doe',
        age: '25',
        token: 'askldaskld123klm'
    }

how do i spread all keys execpt one?

I have tried doing this:

    const userData = {
        data.token,
        ...data
    }

But i get this error from eslint.

Parsing error: ',' expected.
  • 1
    Unless you remove the key, you cannot. Spreading is all or nothing. See [How can I clone a JavaScript object except for one key?](https://stackoverflow.com/q/34698905) – VLAZ Feb 25 '23 at 16:59
  • 1
    It's not 100% clear what you want, but if you want `userData` to be the same object missing the `token` key, then you want `const { token, ...userData } = data;` – Robin Zigmond Feb 25 '23 at 17:03
  • As Robin suggested it looks like you're after [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). – Andy Feb 25 '23 at 17:15
  • An alternative might be to overwrite the property you don't want, i.e. `const userData = { ...data, token: undefined }`. `userData` will still have a `token` property but it will be undefined. – Lennholm Feb 25 '23 at 17:51

1 Answers1

1

If you want to replace the value of the token property in the data object with a new value, You need to specify a key for the data.token value like this

const userData = {
    token: data.token,
    ...data,
};

Or if you want to remove the token property from the data object. You can use object destructuring to achieve this.

const {token, ...userData} = data;

This will create a new object called userData that contains all properties from the data object except for the token property.

Pervez Ali
  • 21
  • 1
  • 3
  • Just one note: if you're using ESLint it will probably complain about the `token` constant that never gets used, even though it's deliberately defined and discarded in order to exclude it from `userData` – Lennholm Feb 25 '23 at 17:48