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 }]
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).
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.
The spread operator lets us expand elements such as objects and arrays. Lets see how it works. This way of using the spread operator is also handy for overwriting properties in existing objects.
You could use Rest syntax in Object Destructuring to get all the properties except drugName
to a rest
variable like this:
const transformedResponse = [{ drugName: 'HYDROCODONE-HOMATROPINE MBR', drugStrength: '5MG-1.5MG', drugForm: 'TABLET', brand: false }, { drugName: 'HYDROCODONE ABC', drugStrength: '10MG', drugForm: 'SYRUP', brand: true }] const output = transformedResponse.map(({ drugName, ...rest }) => rest) console.log(output)
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 with 0
as key in loggerResponse
:
const array = [{ id: 1 }, { id: 2 }] console.log({ ...array })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With