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 ?
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] .
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] .
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.
Either use person.attributes[attr_name]
or person.read_attribute(att_name)
, or even shorter then this is person[attr_name]
.
send is the method you're looking for.
If doing this using send
address = person.send("function_name" + "attr_name")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With