Javascript get object key name
ECMAscript edition 5 also offers you the neat methods Object.keys()
and Object.getOwnPropertyNames()
.
So
Object.keys( buttons ); // ['button1', 'button2'];
This might be better understood if you modified the wording up a bit:
var buttons = {
foo: 'bar',
fiz: 'buz'
};
for ( var property in buttons ) {
console.log( property ); // Outputs: foo, fiz or fiz, foo
}
Note here that you're iterating over the properties of the object, using property
as a reference to each during each subsequent cycle.
MSDN says of for ( variable in [object | array ] )
the following:
Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.
Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.
An ES6 update... though both filter and map might need customization.
Object.entries(theObj)
returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.
Saves a ton of work on iterating over parts of an object Object.keys(theObj)
, or Object.values()
separately.
const buttons = {
button1: {
text: 'Close',
onclick: function(){
}
},
button2: {
text: 'OK',
onclick: function(){
}
},
button3: {
text: 'Cancel',
onclick: function(){
}
}
}
list = Object.entries(buttons)
.filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options
.map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)
console.log(list)
Change alert(buttons[i].text);
to alert(i);