Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  24] [ 5]  / answers: 1 / hits: 30460  / 11 Years ago, wed, may 15, 2013, 12:00:00

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
});

More From » object

 Answers
206

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


[#78210] Tuesday, May 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cody

Total Points: 679
Total Questions: 111
Total Answers: 111

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;