0

I need to update Existing object conditionally using spread operator. Below my code

      const resetPerson: any = {...person, name: '', age: '', location && location : '' };

if location key exist in person object then only clear location else no need to add location property.

How can I do that.

Nagasai
  • 11
  • 6
  • 1
    `const resetPerson: any = location ? { ...person, name: '', age: '', location : '' } : { ...person, name: '', age: '' } ;` – eroironico Jul 07 '22 at 10:13
  • @Nick looks good Thanks. Is there any way to optimize code. – Nagasai Jul 07 '22 at 10:19
  • @Nagasai What do you want to optimize? – jabaa Jul 07 '22 at 10:28
  • @jabaa I don't want to repeat keys `const resetPerson: any = { ...person, name: '', age: '' }; person.location && {....resetPerson, location: ''}` kind of this example – Nagasai Jul 07 '22 at 10:34

1 Answers1

1

You can conditionally add an object property like this:

const resetPerson: any = {
  ...person,
  name: '',
  age: '',
  ...('location' in person && { location: '' })
};
Valentin Rapp
  • 432
  • 6
  • 11