简体   繁体   中英

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.

Also, MooTools and ES5 provide Object.keys

var obj = {
    myName: { }
    yourName: { }
};

console.log(Object.keys(obj)); // ['myName', 'yourName']; 

I would also advise you to use Object.each(obj, fn(value, key, obj){}) for iterator. see http://mootools.net/core/docs/1.5.1/Types/Object#Object:Object-each

it gives you a closure so variables are not re-declared and dont interfere with each other.

var keys = [];
Object.each(contacts, function(value, key){
    var newRow = new Element('li.contact').set('html', '{forename} {surname}'.substitute(value)),
        innerSpan = new Element('span.details').set('html', '{phone}, {email}'.substitute(value)).inject(newRow);

    newRow.addEvent("click", this.setFromContact.bind(this, value)).inject($(this.list));
    keys.push(key); // avoids extra Object.keys call
}, this);

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;
}
// Variable with the "myName" object    
var myVariable = contacts[key];

key variable is a string, such as "myName"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM