Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get Object's attribute

How do I dynamiclly get an attribute value for an activerecord object?

for example I have a variable named attr_name.
I want to do something like this:

person = Person.find(1)
attr_name = "address"
address = person.<function_name>(attr_name)

which function_name can be used ?

like image 340
Eyal R Avatar asked Feb 28 '12 11:02

Eyal R


People also ask

How do you access object properties dynamically?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How do you access objects using variables?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

How do I create a dynamic object key?

To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature. The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.


3 Answers

Either use person.attributes[attr_name] or person.read_attribute(att_name), or even shorter then this is person[attr_name].

like image 194
Samnang Avatar answered Oct 04 '22 07:10

Samnang


send is the method you're looking for.

like image 44
Syed Aslam Avatar answered Oct 04 '22 05:10

Syed Aslam


If doing this using send

address = person.send("function_name" + "attr_name")
like image 43
Abram Avatar answered Oct 04 '22 07:10

Abram