'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
}]


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

Another option is to write a generic function, removeKey -

const removeKey = (k, { [k]:_, ...o }) =>
  o

const 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 } = {}) =>
  o

const 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 }, {} ]

Solution 4:[4]

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const {
  b,
  ...noB // assigns remaining keys to a new `noB` object
} = myObject;
console.log(noB); // => { a: 1, c: 3 }

Solution 5:[5]

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:

const response = [{
    drugName: 'HYDROCODONE-HOMATROPINE MBR',
    drugStrength: '5MG-1.5MG',
    drugForm: 'TABLET',
    brand: false
}]

console.log("response", response)

const removeNamesFromResponse = (response) => {
  return response.map(drug => {
    const { drugName, ...drugWithoutName } = drug
    return drugWithoutName
  })
}

const responseWithoutNames = removeNamesFromResponse(response)

console.log("responseWithoutNames", responseWithoutNames)

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

Solution 6:[6]

Another one line solution will be,

return {...(delete obj.del && obj)} 

Solution 7:[7]

You can use the spread operator and simply assigning undefined to the key you don't want:

const transformedResponse = [{
drugName: 'HYDROCODONE-HOMATROPINE MBR',
drugStrength: '5MG-1.5MG',
drugForm: 'TABLET',
brand: false
}];

const output = transformedResponse.map((response) => ({
  ...response,
  drugName: undefined
}))

console.log(output);

Solution 8:[8]

If you have property drugName in every object of transformedResponse array you can use Array.map() to generate a new array without drugName property:

Example:

const transformedResponse = [
  {
    drugName: 'HYDROCODONE-HOMATROPINE MBR',
    drugStrength: '5MG-1.5MG',
    drugForm: 'TABLET',
    brand: false
  },
  {
    drugName: 'TEST',
    drugStrength: '7MG-1.9MG',
    drugForm: 'TABLET',
    brand: false
  }
];

const loggerResponse = transformedResponse.map(o =>
{
    let clone = Object.assign({}, o);
    return (delete clone.drugName, clone);
});

console.log(loggerResponse);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 Mulan
Solution 4 ryanm
Solution 5 Andrew Koster
Solution 6 Riken Shah
Solution 7 Beachhouse
Solution 8