0

I'm trying to create a new object from values that have been passed in from a function, however, when I try to do so - I get the literal variable name put into state. For example:

updateReactions = (foods, reaction) => {
        foods.forEach((food) => {
            if (!this.state.reactions[food]) {
                let newReaction = { food: { reaction : 1 } };
        });
    };

And if I call updateReactions(banana, happy), it'll create an object creating

{ food: { reaction : 1 } } ;

This outputs to a new object literally showing food: reaction: 1, but I would like for it to create

{ banana: { happy : 1 } }

Thank you!

Candace
  • 53
  • 6
  • You need to assign it as a [computed property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015) `let newReaction = { [food]: { [reaction] : 1 } };` – pilchard Sep 01 '21 at 22:23
  • What you're doing here is just literally creating a variable newReaction. That's just a box. It contains the object with one field called food. Return it... Or in your case, rather assign. – B_Joker Sep 01 '21 at 22:26
  • 1
    Does this answer your question? [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – pilchard Sep 01 '21 at 22:26

2 Answers2

1

You can use the object key as it follows:

let newReaction = { [food]: { [reaction] : 1 } };

That will refer to the parameters passed.
In the example provided, you told the variable newReaction that it must be an object that has a food object which must have a reaction key with the value of one, you were not referring to the actual function parameters :)

marius florescu
  • 632
  • 3
  • 14
1

Replace: let newReaction = { food: { reaction: 1 } };

For: let newReaction = { [food]: { [reaction]: 1 } };

Dharman
  • 30,962
  • 25
  • 85
  • 135
IOrch-K
  • 23
  • 1
  • 7