Candace
Candace

Reputation: 53

How do I create an object from parameters passed in?

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!

Upvotes: 0

Views: 900

Answers (2)

IOrch-K
IOrch-K

Reputation: 23

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

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

Upvotes: 1

marius florescu
marius florescu

Reputation: 672

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

Upvotes: 2

Related Questions