Ottenere i nomi dei membri di un array in JavaScript dinamicamente in fase di esecuzione
-
16-11-2019 - |
Domanda
Prima di tutto non sono sicuro che sia effettivamente possibile in JavaScript, ma ancora ho sentito che vale la pena chiedere.
Ok, quindi quello che sto cercando di fare è ottenere i nomi dei membri di un array (o oggetto come si potrebbe dire) dinamicamente in runtime.
Lasciami spiegare.Ho un oggetto come questo:
Results :-
member_name1 : value_1
.
member_name2 : value_2
.
member_name3 : value_3
Qui, Result
è il nome dell'oggetto che ha membri come member_name1
, member_name2
, ecc. E THE ha valori come value_1
e value_2
rispettivamente.Quello che sto cercando di fare è ottenere il nome dei membri come member_name1
questo in runtime;non è un valore.Accedo il valore con Results.member_name1
in generale.
Spero di essere in grado di ritrarre il problema!
Di seguito è riportato uno screenshot dell'oggetto:
http://i.stack.imgur.com/dzagm.png .
Grazie!
Soluzione
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.
Altri suggerimenti
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.