How to delete property from spread operator?

JavascriptArraysEcmascript 6

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

Another one line solution will be,

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

Solution 7 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhussainView Question on Stackoverflow
Solution 1 - JavascriptadigaView Answer on Stackoverflow
Solution 2 - JavascriptDhruvil21_04View Answer on Stackoverflow
Solution 3 - JavascriptMulanView Answer on Stackoverflow
Solution 4 - Javascriptrufai demirView Answer on Stackoverflow
Solution 5 - JavascriptAndrew KosterView Answer on Stackoverflow
Solution 6 - JavascriptRiken ShahView Answer on Stackoverflow
Solution 7 - JavascriptYonatan NaorView Answer on Stackoverflow
Solution 8 - JavascriptShiderszView Answer on Stackoverflow