Search code examples
javascriptmootools

get name of array key


I have a JSON like this:

{
        "myName":{
                 "forename":"alf",
                 "surname":"cool",
                 "phone":"000000000000",
                 "email":"mail@com"
},.....

My code where I can access each key

 for (var key in contacts) {
                          if (contacts.hasOwnProperty(key)) {
                                var newRow = new Element('li');
                                newRow.addClass('contact');
                                newRow.set('html', contacts[key].forename + ' ' + contacts[key].surname);

                                var innerSpan = new Element('span').set('html', contacts[key].phone + ', ' + contacts[key].email);
                                innerSpan.addClass('details');
                                innerSpan.set('html', contacts[key].phone + ', ' + contacts[key].email);
                                innerSpan.inject(newRow);

                                newRow.addEvent("click", this.setFromContact.bind(this, contacts[key]));
                                newRow.inject($(this.list));
                               // save myName to a variale here!!

                          }
                 }

Now I want to save "myName" to a variable.


Solution

  • You can test the value of the keys and if the value is "myName" you can save it into a variable.

    var myName = '';
    for (var key in contacts) {
        if(key == "myName")
            myName = key;
    }