How to Convert from a String to Object Attribute Name

How to convert from a string to object attribute name?

Let's say column_array[i] = "foo", for an example.

If you want to call the method r.foo, use Object#send:

 r.send(column_array[i], arg1, arg2, arg3, ...)

If you want to access r's instance variable @foo, use Object#instance_variable_get and Object#instance_variable_set:

 r.instance_variable_get('@'+column_array[i])
r.instance_variable_set('@'+column_array[i], new_value)

In this case we have to prepend the given name with an @ sigil, since that is required at the start of all instance variable names.

Since this is rails, and there's a whole lot of ActiveRecord magic going on with your models (and I'm guessing Student is a subclass of ActiveRecord::Base) you probably want to use the former, since ActiveRecord creates methods to access the database, and the values stored in instance variables may not be what you want or expect.

I'll use an example from some test data I've got lying around:

% script/console
Loading development environment (Rails 2.3.2)
irb> Customer
#=> Customer(id: integer, date_subscribed: datetime, rental_plan_id: integer, name: string, address: string, phone_number: string, credit_limit: decimal, last_bill_end_date: datetime, balance: decimal)
irb> example_customer = Customer.find(:all)[0]
#=> #<Customer id: 6, date_subscribed: "2007-12-24 05:00:00", rental_plan_id: 3, name: "Evagation Governessy", address: "803 Asbestous St, Uneradicated Stannous MP 37441", phone_number: "(433) 462-3416", credit_limit: #<BigDecimal:191edc0,'0.732E3',4(12)>, last_bill_end_date: "2009-05-15 04:00:00", balance: #<BigDecimal:191e870,'0.743E3',4(12)>>
irb> example_customer.name
#=> "Evagation Governessy"
irb> field = 'name'
#=> "name"
irb> example_customer.instance_variable_get(field)
NameError: `name` is not allowed as an instance variable name
from (irb):8:in `instance_variable_get`
from (irb):8
irb> example_customer.instance_variable_get('@'+field)
#=> nil
irb> example_customer.send(field)
#=> "Evagation Governessy"
irb> example_customer.send(field+'=', "Evagation Governessy Jr.")
#=> "Evagation Governessy Jr."
irb> example_customer.send(field)
#=> "Evagation Governessy Jr."
irb> example_customer.name
#=> "Evagation Governessy Jr."

So you can see how #send(field) accesses the record information, and trying to access the attributes doesn't.
Also, we can use #send(field+'=') to change record information.

Convert string to object property name

That's because typescript infers the type of madeObject to be {} (empty object). Just give it a more explicit type

interface MyObject {
title:string;
}

let madeObject:Partial<MyObject> = {};
const fieldName:keyof MyObject = 'title';
madeObject[fieldName] = 'hello';

If you know that an object will have keys, but you don't know the name of the keys (maybe because they are only known at runtime), then you can use typescripts dynamic keys

interface MyObject {
// left side is the type of the key (usually string or symbol)
// right side is the type of the property (use "any" if you don't know)
[key:string]: string;
}

let madeObject:MyObject = {};
const fieldName:string = 'title';
madeObject[fieldName] = 'hello';

// Or you can make the interface Generic, if you have this situation a lot:

interface MyObjectGeneric <V = any, K = string> {
[key:K]: V;
}

let madeObject:MyObjectGeneric/* <string> */ = {}; // Adding <string> would narrow the return type down to string
const fieldName:string = 'title';
madeObject[fieldName] = 'hello';

Another way to solve this would be to remove the type safety all together (this is NOT recommended and makes typescript lose its purpose)

let madeObject:any = {}; // declares that madeObject could be anything
const fieldName = 'title';
madeObject[fieldName] = 'hello';

// alternatively:

let madeObject2 = {}; // Type inferred as "{}"
(madeObject2 as any)[fieldName] = 'hello'; // Removes type safety only temporarily for this statement

Convert string value to object property name

Use ['propname']:

objPosition[txtCol] = "whatever";

Demo: http://jsfiddle.net/hr7XW/

How can I convert string value to object property name

Reflection is the right tool:

PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);

Python string to attribute

Use the builtin function getattr.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

In Javascript, how to convert a string to a property name?

Just use a computed property:

return myglobalobject[mystring];

This is a generalization of the fact that property accesses using dot notation are the same as accessing with brackets and a string literal:

obj.prop === obj["prop"];

So when you have something that isn't a string literal, just use the bracket notation.

Get object property name as a string

Yes you can, with a little change.

function propName(prop, value){
for(var i in prop) {
if (prop[i] == value){
return i;
}
}
return false;
}

Now you can get the value like so:

 var pn = propName(person,person.first_name);
// pn = "first_name";

Note I am not sure what it can be used for.

Other Note wont work very well with nested objects. but then again, see the first note.

How to access object attribute given string corresponding to name of that attribute

There are built-in functions called getattr and setattr

getattr(object, attrname)
setattr(object, attrname, value)

In this case

x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)


Related Topics



Leave a reply



Submit