2

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 2

4

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: "[email protected]",
  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; }

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.