我有一个像这样的JSON:
{
"myName":{
"forename":"alf",
"surname":"cool",
"phone":"000000000000",
"email":"mail@com"
},.....
我可以访问每个密钥的代码
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!!
}
}
现在我想将“myName”保存到变量中。
答案 0 :(得分:2)
此外,MooTools和ES5提供Object.keys
var obj = {
myName: { }
yourName: { }
};
console.log(Object.keys(obj)); // ['myName', 'yourName'];
我还建议你使用Object.each(obj, fn(value, key, obj){})
作为迭代器。见http://mootools.net/core/docs/1.5.1/Types/Object#Object:Object-each
它给你一个闭包,所以变量不会被重新声明,也不会相互干扰。
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);
答案 1 :(得分:1)
您可以测试密钥的值,如果值是“myName”,您可以将其保存到变量中。
var myName = '';
for (var key in contacts) {
if(key == "myName")
myName = key;
}
答案 2 :(得分:1)
// Variable with the "myName" object
var myVariable = contacts[key];
键变量是一个字符串,例如“myName”