Getting the names of members of an array in javascript dynamically at runtime
-
16-11-2019 - |
Question
First of all I am not sure whether it is actually possible in javascript, but still I felt it's worth asking.
Ok, so what I am trying to do is get the names of the members of an array (or object as you might say) dynamically at runtime.
Let me explain. I have an object like this :
Results :-
member_name1 : value_1
member_name2 : value_2
member_name3 : value_3
Here, Result
is the name of the object which has members like member_name1
, member_name2
, etc and theu have values like value_1
and value_2
respectively. What I am trying to do is get the name of the members like member_name1
this at runtime; not it's value. I access the value by Results.member_name1
generally.
I hope I am able to portray the issue!
Below is a screenshot of the object :
http://i.stack.imgur.com/dzAgm.png
Thanks!
Solution
Assuming obj
is your object, you can get the names of all its properties this way:
var names = [];
for(var name in obj) {
names.push(name);
}
However, be aware that this will also pick up any extensions that have been made to obj
through the prototype
property of its class. If you want to exclude these and only get the properties defined on obj
itself, you can filter them out with
for(var name in obj) {
if(obj.hasOwnProperty(name)) {
names.push(name);
}
}
More information on for...in
on MDN.
OTHER TIPS
You can access them using JavaScript for construct. Consider the following:
var member_names = [],
data = {
foo1: 'bar1',
foo2: 'bar2',
foo3: 'bar3',
};
for (var i in data) {
member_names.push(i);
}
console.log(member_names);
Here we have an empty array called *member_names* and your data object. In our loop, i will reference the property name, so you can push it onto the member_names array and then have access to them all there.