0

I've built a simple object which simulates a table following the answers to this question: Store a table of data in a JavaScript variable

The modeled table is something like this:

         | Tension | Dissonance | Modal |
value_a  | 1.234   |  5.324     | 7.24  |
value_b  | 3       | 6.341      | 27.3  |

I would like to access and retrieve the Tension, Dissonance and Modal values for a single entry value_a (for example), passing to a function the selected parameter.

So far i tried something like this:

var myObj = {
    value_a:{D:3.944,T:1.1606,M:5.3893},
    value_b:{D:2,T:6.543,M:5.10},
    myMethod: function(params) {
      console.log(params);
      console.log(this.params); //since this.value_a is a correct expression, i thought this might work, but it doesn't
    }
};

I would like to be able to do a call like myObj.myMethod("value_a") and then return the value of [D,T,M] associated with value_a

I tried this way (and i know it doesn't work), but i don't know if it's possible to use a parameter as selector of an attribute.

If not, how could i pass the parameter and return the relative attribute values?

0

1 Answer 1

1

You can do this by using bracket notation such as someObject[property_name]. Inside the brackets would need to be a string or Symbol.

var myObj = {
    value_a: { D:3.944, T:1.1606, M:5.3893 },
    value_b: { D:2, T:6.543, M:5.10 },
    myMethod: function(params) {
      console.log(params);
      console.log(this[params]);
    }
};

myObj.myMethod("value_a");
myObj.myMethod("value_b");
myObj.myMethod("foo"); // undefined

Hopefully that helps!

Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly! Can i ask you why it's different from the dot notation? Are they equivalent? I mean, myObj.value_a and myObj[value_a] will behave in the same way?
They are not equivalent and will not behave in the same way. With bracket notation, the value inside the brackets is evaluated prior to attempting to access that respective object property. If you need to dynamically access object properties, you would use bracket notation.
So the dot notation is used for (maybe i'm using the term improperly) static elements? If i want to call a fixed variable/method (and i now a priori the name) i'll use myObj.element, while if i need to make it dependent by an external parameter, i'll use myObj[param] right?
Sure, it can be seen that way. At a basic level, if you know the exact/static properties you need to access, you can use dot notation or ES6 object destructuring assignment. If you need to access properties dynamically (or externally dependent as you describe), then you can use bracket notation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.