I want to delete drugName from the response but it is not happening any idea how to delete property from spread operator ? main.js
const transformedResponse = transformResponse(response);
const loggerResponse = {...transformedResponse};
delete loggerResponse[drugName];
console.log("LOGGER>>>>", loggerResponse);
logger().info('Drug Price Response=', { ...loggerResponse, memberId: memberId, pharmacyId: pharmacyId });
\ data
LOGGER>>>> {
'0': {
isBrand: false,
drugName: 'test drug',
drugStrength: '5 mg 1 5 mg',
drugForm: 'Tablet',
}
}
transformResponse
[{
drugName: 'HYDROCODONE-HOMATROPINE MBR',
drugStrength: '5MG-1.5MG',
drugForm: 'TABLET',
brand: false
}]
This is the most succinct and immutable way that I've found. You simply destructure the object into two parts: one part is the property you're trying to remove (
drugName
in this case), and the other part is the rest of the object, that you want to keep (drugWithoutName
in this case).Once you've done that, you can abandon the property that has been removed, abandon the original object, and use the new object (
drugWithoutName
in this case) that has all of the remaining fields.Coming up with the syntax isn't obvious, but it makes sense once you see it:
These articles explain the concept further:
https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90
https://github.com/airbnb/javascript/blob/master/README.md#objects--rest-spread
You could use Rest syntax in Object Destructuring to get all the properties except
drugName
to arest
variable like this:Also, when you spread an array inside
{}
, you get an object with indices of the array as key and the values of array as value. This is why you get an object with0
as key inloggerResponse
:1 line solution using ES9 Object Rest Operator
Another option is to write a generic function,
removeKey
-The function can be easily adapted to remove multiple keys, if necessary -
If you have property
drugName
in every object oftransformedResponse
array you can use Array.map() to generate a new array withoutdrugName
property:Example: