Reputation: 53
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.
Upvotes: 2
Views: 795
Reputation: 1384
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);
Upvotes: 0
Reputation: 48693
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; }
Upvotes: 4