Get Properties and Values from Unknown Object

Get properties and values from unknown object

This should do it:

Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
object propValue = prop.GetValue(myObject, null);

// Do something with propValue

How to get property value in js object when key is unknown

I've found the answer.

for (var key in a) {
console.log(a[key][Object.keys(a[key])[0]].p); // 81.25

How to get value of unknown properties (part solved already with reflection)

this is how you can do it. (by the way, your code might error out on "dictionary key not being unique" since the second userItem will try to add the same property name to the dictionary. you might need a List<KeyValuePair<string, string>>)

        foreach (var property in theProperties)
// gets the value of the property for the instance.
// be careful of null values.
var value = property.GetValue(userItem);

userDetails.Add(property.Name, value == null ? null : value.ToString());

and by the way, if you're in MVC context, you could take a reference to System.Web.Routing and use the following snippet.

foreach (var userItem in UserItems)
// RVD is provided by routing framework and it gives a dictionary
// of the object property names and values, without us doing
// anything funky.
var userItemDictionary= new RouteValueDictionary(userItem);

Access generated properties with unknown property names in array of objects

You can use Object.keys()[0] to get the key, then use the key to get the value.


var myData = [{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}];
for (var i = 0; i < myData.length; i++) { var myObject = myData[i]; var firstKey = Object.keys(myObject)[0]; var value = myObject[firstKey];
console.log(firstKey + ": " + value);}

Get properties from class object using reflection where property should be public and having get or get and set both

You should not be using the bitwise AND (&), but the bitwise OR (|):

var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);

Using reflection to cast unknown object to generic class

Take a look at this:

public static void Reflecting(object obj)
foreach (var pi in obj.GetType().GetProperties())
if (pi.PropertyType.BaseType.IsGenericType
&& pi.PropertyType.BaseType.GetGenericTypeDefinition()
== typeof(GenericClass<>))
var propValue = pi.GetValue(obj);
if (propValue != null)
var description = propValue.GetType()

I think this is what you need.

Related Topics

Leave a reply