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;
-
possible duplicate of Dynamic object property nameFelix Kling– Felix Kling2013年02月21日 18:07:36 +00:00Commented Feb 21, 2013 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. Thankschris– chris2013年02月21日 18:32:34 +00:00Commented Feb 21, 2013 at 18:32
-
No worries. It's a quite common question in fact. You might find my q/a here also informative: stackoverflow.com/questions/11922383/….Felix Kling– Felix Kling2013年02月21日 18:36:22 +00:00Commented Feb 21, 2013 at 18:36
3 Answers 3
Remove the dot. Use
obj[arr[0]] = some_value;
I'd suggest you to read Working with objects from the MDN.
4 Comments
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.You could try
obj[arr[0]] = some_value;
i.e. drop the dot :)
Comments
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;
1 Comment
obj.arr.