Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a JavaScript's object property without knowing that property name

Tags:

Situation

I have a JSON object which is returned. And Below is an example of one. The who in this particular example can change to whatever property name is required. So for example next time this will be name rather than who

 [{"who":"Arthur"},{"who":"Craig"},{"who":"Dan"},{"who":"Daniel"},{"who":"Frank"},{"who":"Ian"},{"who":"jamie"},{"who":"Jason"},{"who":"jaz"},{"who":"Liam"},{"who":"Paul"},{"who":"Shaun"},{"who":"Wayne"}] 

Problem

In my JS I need to be able to refer to the property and access its data without using its name as the name will always be something different.

What I have tried

data.forEach(function(m){     console.info(m); // Object { who="Craig"}     console.info(m.who); // Craig, as expected     console.info(m[0]); // now not sure who to get it if who changes to name }); 
like image 775
Jamie Hutber Avatar asked May 15 '13 23:05

Jamie Hutber


People also ask

How do you dynamically access an object property?

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 find the property name of an object?

To get object property name with JavaScript, we use the Object. keys method. const result = Object. keys(myVar); console.

How many ways you can access the object properties?

An object property can be accessed in two ways. One is . property and the other is [property].


1 Answers

Object.keys(m)[0] should return the first enumerable property name in the object m.

So if m = {"who": "Arthur"}; then m[Object.keys(m)[0]] will be "Arthur".

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys


Alternatively: Object.values(m)[0]. See Object.values

like image 181
Rick Viscomi Avatar answered Nov 01 '22 22:11

Rick Viscomi