我有一些对象的数组,我想以某种方式组织它们
这是我在JavaScript中的数组:
doctors = [
{"prop":"A","hour":"08:00"},
{"prop":"A","hour":"08:00"},
{"prop":"A","hour":"08:00"},
{"prop":"A","hour":"08:00"},
{"prop":"A","hour":"08:00"},
{"prop":"A","hour":"08:00"},
{"prop":"B","hour":"08:00"},
{"prop":"B","hour":"08:00"},
{"prop":"B","hour":"08:00"},
{"prop":"C","hour":"08:00"},
{"prop":"C","hour":"08:00"} ]
这个数组来自我的后端(PHP)的ajax调用,我想把它改成这样:
doctors = [
{"prop":"A",
"hour":"10:00"
"hour":"12:00"
"hour":"23:00"
"hour":"12:00"
"hour":"02:00"
"hour":"01:00"
},
{"prop":"B",
"hour":"18:00"
"hour":"03:00"
"hour":"01:00"
"hour":"08:00"
},
{"prop":"C",
"hour":"04:00"
"hour":"12:00"
"hour":"08:12"
"hour":"04:00"
},
]
我该怎么做?我的意思是提取类似的键并将所有类似的键压缩成一个值数组???
如果它是importtant,这是我在PHP中的后端:
if($result = $db->query($sql)){
$hours = array();
while($row = $result->fetch_object()){
$drid = $row->id;
$hour = $row->b_h;
$matid = $row->mid;
$month = $row->b_m;
$day = $row->b_d;
$hours[] = [
'prop'=>$drid.'-'.$matid.'-'.$month.'-'.$day,
'hour'=>$hour
];
}
echo (json_encode($hours)) ;
}
数字并不真实,为简单起见,我将真正的道具更改为A B C
如果它有所帮助,稍后,我想在角度js中使用ng-repeat中的每个道具是这样的:
<li ng-repeat="hour in propA">hour</li>
或者:
<li ng-repeat="hour in propB">hour</li>
感谢
答案 0 :(得分:0)
编辑以适应更改的问题
var doctors = [
{"prop":"A","hour":"08:00"},
{"prop":"A","hour":"08:10"},
{"prop":"A","hour":"08:20"},
{"prop":"A","hour":"08:30"},
{"prop":"A","hour":"08:40"},
{"prop":"A","hour":"08:50"},
{"prop":"B","hour":"09:00"},
{"prop":"B","hour":"09:10"},
{"prop":"B","hour":"09:20"},
{"prop":"C","hour":"10:00"},
{"prop":"C","hour":"10:10"} ];
var doctors_morph = {};
for(var i in doctors) {
if(typeof doctors_morph[doctors[i].prop] == 'undefined') {
doctors_morph[doctors[i].prop] = [];
}
doctors_morph[doctors[i].prop].push(doctors[i].hour);
}
这样你可以通过以下方式获得医生:
doctors_morph['A'];
doctors_morph['B'];
doctors_morph['C'];
您的示例结果如下所示:
doctors_morph = {
'A' : {
['8:00','8:10','8:20','8:30','8:40','8:50']
}
// etc
}
AS for PHP,要跳过上面你可以使用:
if($result = $db->query($sql)){
$doctors = array();
while($row = $result->fetch_object()){
$drid = $row->id;
$hour = $row->b_h;
$matid = $row->mid;
$month = $row->b_m;
$day = $row->b_d;
if(!isset($doctors[$drid.'-'.$matid.'-'.$month.'-'.$day]) OR !is_array($doctors[$drid.'-'.$matid.'-'.$month.'-'.$day]))
$doctors[$drid.'-'.$matid.'-'.$month.'-'.$day] = array();
$doctors[$drid.'-'.$matid.'-'.$month.'-'.$day][] = $hour;
}
echo (json_encode($doctors)) ;
}