Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 436
chris Avatar asked Feb 21 '13 17:02

chris


2 Answers

Remove the dot. Use

obj[arr[0]] = some_value;

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

like image 163
Denys Séguret Avatar answered Sep 29 '22 07:09

Denys Séguret


You could try

obj[arr[0]] = some_value;

i.e. drop the dot :)

like image 22
Mike Hogan Avatar answered Sep 29 '22 07:09

Mike Hogan