I come from the Ruby world. How do I use the string value of an array as a property of an object? Example ..
obj.myarray[0] = 1.00 // obviously this does not work, can you pro make it work?
obj = {
val1: 1.00, val2: 2.00}
myarray = ["val1"]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Short answer: I believe the syntax you are looking for is this:
This assumes you have an array,
myarray, and the first item in the array (index 0) has the name of the key you want to use with yourobjobject.Note that
= 1.00is an assignment, so it will store that value in your object. For comparison you want the==or===operators.Long answer:
The code from your question:
creates an object called
objwith two properties namedval1andval2. These properties can be accessed like this:Where the dot syntax only works with property names that follow the rules for JavaScript identifier names. With the bracket and string syntax you can use just about any string as a property name.
Then
Creates an array with one element, the string “val1”. So as in my “short answer”, to access a property of the object using an element from the array you say:
(Where the index, 0, can be another variable if desired.)
You might like to read this: https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects (Also, note that in JavaScript arrays are a special type of object intended to be used with numeric indices that does not really correspond directly with the “associative arrays” of other languages – a “plain” JS object is closer to an “associative array”.)
Note also that the values you are storing,
1.00and2.00, being numeric, will be returned as simply1and2– if you need to retain trailing zeros after the decimal point you’ll need to store them as strings.