chris
chris

Reputation: 36937

JavaScript append to object using array key/value pair

I have an object that I build out dynamically example:

obj = {};
obj.prop1 = 'something';
obj.prop2 = 'something';
obj.prop3 = 'something';

With that I now have a need to take an item from an array and use it to define both the equivalent of "propX" and its value

I thought if I did something like

obj.[arr[0]] = some_value;

That, that would work for me. But I also figured it wouldn't the error I am getting is a syntax error. "Missing name after . operator". Which I understand but I'm not sure how to work around it. What the ultimate goal is, is to use the value of the array item as the property name for the object, then define that property with another variable thats also being passed. My question is, is how can I achieve it so the appendage to the object will be treated as

obj.array_value = some_variable;

Upvotes: 5

Views: 10847

Answers (3)

Marryat
Marryat

Reputation: 535

You are nearly right, but you just need to remove the . from the line:

obj.[arr[0]] = some_value;

should read

obj[arr[0]] = some_value;

Upvotes: 3

Mike Hogan
Mike Hogan

Reputation: 10603

You could try

obj[arr[0]] = some_value;

i.e. drop the dot :)

Upvotes: 3

Denys Séguret
Denys Séguret

Reputation: 382102

Remove the dot. Use

obj[arr[0]] = some_value;

I'd suggest you to read Working with objects from the MDN.

Upvotes: 8

Related Questions