How do you remove a nested property with spread and rest in javascript

Viewed 316

I am trying to remove the 'name' property from registerReqOptions in this code.

const registerReqOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: registerObj.name,
        email: registerObj.email,
        password: registerObj.password
      })
    }

I tried;

const {body: {name}, ...loginReqOptions} = registerReqOptions

but it is removing the whole 'body' property instead of only the nested 'name' one.

What is the correct way to do this using the newer spread and rest syntax?

Thanks.

2 Answers

You have to capture the rest of the body:

const { body: { name, ...restOfBody }, ...loginReqOptions } = registerReqOptions;

And then reassign it:

const copy = {
  ...loginReqOptions,
  body: { ...restOfBody }
};

const registerObj = {
  name: "John Doe",
  email: "john@doe.com",
  password: "foobar"
};

const registerReqOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: {
    name: registerObj.name,
    email: registerObj.email,
    password: registerObj.password
  }
}

const { body: { name, ...restOfBody }, ...loginReqOptions } = registerReqOptions;

const copy = {
  ...loginReqOptions,
  body: { ...restOfBody }
};

console.log(copy);
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you want to use Object.keys() || Object.entries() , you can do something like this:

let registerReqOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: {
    name: 'registerObj.name',
    email: 'registerObj.email',
    password: 'registerObj.password'
  }
}

console.log('Initial ==', registerReqOptions);

const keysAndValues = Object.entries(registerReqOptions);


keysAndValues.forEach(([key, value]) => {
  if (key === 'body' && (value instanceof Object)) {
    delete value['name'];
  }
})


console.log('Modified ==', registerReqOptions);

Related