Javascript get object key name

Javascript

Javascript Problem Overview


How would I get the key name for the follow? E.g I want "button1" and "button2"?

var buttons = {
    button1: {
        text: 'Close',
        onclick: function(){
           
        }
    },
    button2: {
        text: 'Close2',
        onclick: function(){
           
        }
    }
}
 
var i;
for(i in buttons){
    if(buttons.hasOwnProperty(i)){
        alert(buttons[i].text);
    }
} 

I tried using .push() although this didn't work.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

ECMAscript edition 5 also offers you the neat methods Object.keys() and Object.getOwnPropertyNames().

So

Object.keys( buttons );  // ['button1', 'button2'];

Solution 3 - Javascript

Change alert(buttons[i].text); to alert(i);

Solution 4 - Javascript

Variable i is your looking key name.

Solution 5 - Javascript

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)

Solution 6 - Javascript

Here is a simple example, it will help you to get object key name.

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

Solution 7 - Javascript

Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.

function key(int) {
    var j = -1;
    for(var i in this) {
        j++;
        if(j==int) {
            return i;
        } else {
            continue;
        }
    }
}
Object.prototype.key = key;

This is numbered to work the same way that arrays do, to save headaches. In the case of your code:

buttons.key(0) // Should result in "button1"

Solution 8 - Javascript

To retrieve key and value use the below.

 for (let property in buttons) {
    console.log('key:' + property, 'value:'+ buttons[property]);
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn MagnoliaView Question on Stackoverflow
Solution 1 - JavascriptSampsonView Answer on Stackoverflow
Solution 2 - JavascriptjAndyView Answer on Stackoverflow
Solution 3 - JavascriptQuentinView Answer on Stackoverflow
Solution 4 - JavascriptIProblemFactoryView Answer on Stackoverflow
Solution 5 - JavascriptTim PozzaView Answer on Stackoverflow
Solution 6 - JavascriptAkash JainView Answer on Stackoverflow
Solution 7 - JavascriptVXxedView Answer on Stackoverflow
Solution 8 - JavascriptCynthia.BerryView Answer on Stackoverflow