Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete property from spread operator?

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 }] 
like image 804
hussain Avatar asked May 15 '19 18:05

hussain


People also ask

How do you delete a object using the spread operator?

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

How do you remove a property of an object?

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.

How do you remove a property from an array?

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.

Does spread operator overwrite property?

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.


1 Answers

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 })
like image 183
adiga Avatar answered Sep 19 '22 14:09

adiga