Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an object's key and value using a variable from function

Hey I'm trying to remove a key:value pair from state inside a Javascript Object.

It works when I hardcode the key name in the code, but when I try to use a variable from a function call, it does nothing.

Can somebody help me out?

Here's an object example:

  toppingsSelected: {
     "Onion":"true",
     "Mushrooms":"true",
  }

This works, hardcoded:

deleteTopping = toppingName => {

   const { Onion, ...withoutOnion } = toppingsSelected;
   console.log(withoutOnion); // Returns object without onion

  };

This doesn't work:

deleteTopping = toppingName => {


   const toppingName = "Onion"; // Variable gets passed in

   const { toppingName, ...withoutOnion } = toppingsSelected;
   console.log(withoutOnion); // Returns original object, no change made

  };

So I'm basically trying to remove a key from React state but I'm pretty new to Javascript.

How can I make Javascript aware that toppingName is a key?

like image 464
ViktorMS Avatar asked Sep 12 '26 08:09

ViktorMS


1 Answers

Another option is to add square brackets arround toppingName, and assign it to a variable. As @Bergi pointed out in the comments, this option does not mutate toppingsSelected

const toppingsSelected = {
  "Onion":"true",
  "Mushrooms":"true",
};
const toppingName = "Onion";
const {
  [toppingName]: topping,
  ...withoutOnion
} = toppingsSelected;

console.log(JSON.stringify(withoutOnion));

To set the React state, you'd then do this

this.setState({ toppingsSelected: withoutOnion })
like image 105
TFischer Avatar answered Sep 13 '26 21:09

TFischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!