如何只读取此中的类型键值

时间:2014-04-30 06:19:41

标签: javascript

"DoctorA": {"name": "Pharmaceuticals", "title": "Switzerland, 120000 employees","type":"yes"},
"DoctorB": {"name": "Consulting", "title": "USA, 5500 employees","type":"yes"},
"DoctorC": {"name": "Diagnostics", "title": "USA, 42000 employees","type":"no"},
"DoctorD": {"name": "Fin Serv. & Wellness", "title": "South Africa,  employees","type":"no"}

我正在使用data.speakers。

我想得到每一种医生类型,所以我试过这个。

for (property in data.speakers ) {
   //alert(property) contains all the doctor name.
   //i want type for each doctor indivdually.
  for (key in data.speakers) {
    var doctor = data.speakers[key]; 
    types.push(doctor.type);

}
alert(types.toSource());
}

有没有办法做到这一点。它将以数组格式返回所有数据类型(是,否,是,否)我想要这样,首先我将得到doctorA并将其类型设为是。不是所有值在同一时间。

1 个答案:

答案 0 :(得分:2)

您不需要2个循环,只需要一个循环。你似乎只想要这个:

var names = [];
for (key in data.speakers) {
    var doctor = data.speakers[key]; 
    names.push(doctor.type);
}

事实上,从你的评论来看,它看起来像你想要的那样

var doctorTypes = {}
for (key in data.speakers) {
    var doctor = data.speakers[key],
        type = doctor.type;
    doctorTypes[key] = type;
}

然后doctorTypes["DoctorC"]会给你"no"