简体   繁体   English

如何在 javascript 中删除带有扩展和 rest 的嵌套属性

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

I am trying to remove the 'name' property from registerReqOptions in this code.我正在尝试从此代码中的 registerReqOptions 中删除“名称”属性。

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.但它正在删除整个“body”属性,而不仅仅是嵌套的“name”属性。

What is the correct way to do this using the newer spread and rest syntax?使用较新的传播和 rest 语法执行此操作的正确方法是什么?

Thanks.谢谢。

You have to capture the rest of the body:您必须捕获身体的rest:

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()如果要使用Object.keys() || Object.entries() Object.keys() || Object.entries() , you can do something like this: Object.keys() || Object.entries() ,你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM