3

Trying to delete multiple properties usign spread operator rest destruction, so drugName is being removed but i have nested object mailPrice.copayEmployer that is not getting destructed any idea what is implemented wrong ?

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
  • What is the result you want to achieve? You want to keep the mailPrice property, but remove the copayEmployer property inside it? Commented May 15, 2019 at 21:27
  • @Barmar yes thats correct just want to remove mailPrice.copayEmployer and keep the rest of the object Commented May 15, 2019 at 21:28

2 Answers 2

4

I don't think you can do this with a single variable. You need a nested ...rest variable inside the mailPrice object, and then you have to reconstruct the object.

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

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

Comments

0

This is how you destructure nested object's:

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

4 Comments

I don't think this will do what he wants. ...rest won't contain the rest of the mailPrice object.
yeah this is deleting complete object of mailPrice that i dont want
Fixed now, any better?
@Jack Bashford its not happening , is there any other approach instead of spread operator ?

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.