How to delete property from spread operator?
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 })
1 line solution using ES9 Object Rest Operator
const loggerResponse = { "0": { isBrand: false, drugName: "test drug", drugStrength: "5 mg 1 5 mg", drugForm: "Tablet", },};const { drugName, ...newResponse } = loggerResponse["0"];console.log(newResponse);
Another option is to write a generic function, removeKey
-
const removeKey = (k, { [k]:_, ...o }) => oconst values = [ { a: 1, x: 1 } , { a: 1, y: 1 } , { a: 1, z: 1 } ]console .log (values .map (v => removeKey ("a", v)))// [ { x: 1 }, { y: 1 }, { z: 1 } ]
The function can be easily adapted to remove multiple keys, if necessary -
const removeKey = (k = "", { [k]:_, ...o } = {}) => oconst removeKeys = (keys = [], o = {}) => keys .reduce ((r, k) => removeKey (k, r), o)const values = [ { a: 1, x: 1 } , { a: 1, y: 1 } , { a: 1, z: 1 } ]console .log (values .map (v => removeKeys (['a', 'z'], v)))// [ { x: 1 }, { y: 1 }, {} ]