5

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;
chris
  • 36,115
  • 52
  • 143
  • 252
  • possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) – Felix Kling Feb 21 '13 at 18:07
  • Felix, nice find. I think that does constitue my post here as a dupe. Just didn't find it cause I didn't think of a better phrase to search with. Thanks – chris Feb 21 '13 at 18:32
  • No worries. It's a quite common question in fact. You might find my q/a here also informative: http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value. – Felix Kling Feb 21 '13 at 18:36

3 Answers3

8

Remove the dot. Use

obj[arr[0]] = some_value;

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • will that append to the object an array or leave it as an object? – chris Feb 21 '13 at 17:59
  • @chris: It will add `some_value` to the object and the property name will be the value of `arr[0]`. Maybe you thing *bracket notation* is somehow related to arrays, but it's not. It's just a different way of accessing properties. – Felix Kling Feb 21 '13 at 18:00
  • I should have provided it in the example. But there is a hardcoded array that works as an index that we can append to over time, so rather that in the future search for all the references to what the array provides in context we can change it at the array level rather then the entire code base. – chris Feb 21 '13 at 18:01
  • @dystroy thanks for the additional reference, I think I will give that a read – chris Feb 21 '13 at 18:03
3

You could try

obj[arr[0]] = some_value;

i.e. drop the dot :)

Mike Hogan
  • 9,933
  • 9
  • 41
  • 71
3

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;

Marryat
  • 535
  • 3
  • 11