如何使用JS传播剩余破坏删除嵌套属性?

时间:2019-05-15 21:18:53

标签: javascript arrays object ecmascript-6

试图删除多个属性,以销毁操作符,从而销毁了药名,但我删除了嵌套的对象mailPrice.copayEmployer,但并没有破坏任何实现错误的主意?

main.js

const transformedResponse = transformResponse(response);
  const loggerResponse = transformedResponse.map(
      ({drugName, mailPrice.copayEmployer, ...rest}) => rest
  );

transformedResponse

[{
        "isBrand": true,
        "drugName": "Lipitor",
        "drugStrength": "80 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "copayEmployer": 0
        }
    }, {
        "isBrand": true,
        "drugName": "Metformin",
        "drugStrength": "500 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "copayEmployer": 50
        }
    }

]

2 个答案:

答案 0 :(得分:0)

这是您解构嵌套对象的方式:

.map(({ drugName, mailPrice: { copayEmployer, ...restMail }, ...rest }) => ({ mailPrice: { ...restMail }, ...rest});

答案 1 :(得分:0)

我认为您不能使用单个变量来完成此操作。您需要在...rest对象内嵌套mailPrice嵌套变量,然后必须重新构造对象。

const transformedResponse = [{
  "isBrand": true,
  "drugName": "Lipitor",
  "drugStrength": "80 mg",
  "drugForm": "Tablet",
  "mailPrice": {
    "copayEmployer": 0,
  }
}, {
  "isBrand": true,
  "drugName": "Metformin",
  "drugStrength": "500 mg",
  "drugForm": "Tablet",
  "mailPrice": {
    "copayEmployer": 50
  }
}];

const loggerResponse = transformedResponse.map(
  ({
    drugName,
    mailPrice: { copayEmployer, ...mailPriceRest},
    ...rest
  }) => ({mailPrice: {...mailPriceRest}, ...rest})
);

console.log(loggerResponse);